Anyway, as to why that causes a segment fault: you are creating, on the stack, an array of up to 10^9 items, each of type long long. A long long takes up 8 bytes on most machines, so this eats up 8\times 10^9 bytes of stack which is approx 7.45 GB, which is huge - far more than is available. Hence, the crash.
Thanks for the explanation That was an useful info. I was actually trying to fix my solution without unlocking the editorial. I will go and check the editorial now… thanks.
it was a good question . had to find Fine balance between Time and Space.
i learned a lot in this question.
readibilty is not so good, if it helps u. here’s my code:
#include<bits/stdc++.h> #define ll long long int
#include<unordered_map>
using namespace std;
int main() {
int n, m, s, q, temp, temp2;
cin >> n >> m >> s >> q;
unordered_map <int, bool> my_map;
map <ll, int> my_map2;
for (int j = 0;j < m;j++) ///taking postion of balls
{
cin >> temp;
my_map[temp] = true;
my_map2[temp] = 0;
}
for (int j = 0;j < s;j++)
{
cin >> temp >> temp2;
if ((my_map.find(temp) == my_map.end()) || my_map[temp] == false)
{
if ((my_map.find(temp2) == my_map.end()) || my_map[temp2] == false)
{
;
}
else//temp2 has ball
{
my_map[temp] = true;
my_map2.insert(make_pair(temp, 0));
my_map[temp2] = false;
my_map2.erase(temp2);
}
}
else
{
if ((my_map.find(temp2) == my_map.end()) || my_map[temp2] == false)
{
my_map[temp2] = true;
my_map2.insert(make_pair(temp2, 0));
my_map[temp] = false;
my_map2.erase(temp);
}
else//both has ball
{
;
}
}
}
int count = 0;
for (auto i = my_map2.begin(); i != my_map2.end(); i++)
{
count++;
i->second = count;
}
my_map2[INT64_MIN] = 0;
my_map2[INT64_MAX] = count + 1;
int l, r;
int val1, val2;
for (int i = 0;i < q;i++) {
cin >> l >> r;
if ((my_map[l] && my_map[r]) || (my_map[r]))
{
auto it = my_map2.lower_bound(l);
val1 = (*it).second;
it = my_map2.lower_bound(r);
val2 = (*it).second;
cout << val2 - val1 + 1 << " ";
}
else
{
auto it = my_map2.lower_bound(l);
val1 = (*it).second;
it = my_map2.lower_bound(r);
val2 = (*it).second;
cout << val2 - val1 << " ";
}
}
return 0;