problem link :
https://www.spoj.com/problems/DQUERY/
i applied MO's ALgorithm and i don't know why i am getting TLE please tell what changes i should make in my code
My code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <unordered_map>
#define ll long long int
using namespace std;
vector < pair < ll, pair<ll,ll >> > vec;
std::unordered_map<ll, ll> m;
ll ans=0,bucket;
ll final[200005],a[200005];
bool compar(pair<ll,pair<ll,ll>> p1 , pair<ll,pair<ll,ll>> p2){
if(p1.second.first/bucket!=p2.second.first/bucket)
return p1.second.first/bucket < p2.second.first/bucket;
return p1.second.second<p2.second.second;
}
void add(ll currl){
m[a[currl]]++;;
if(m[a[currl]]==1)
ans++;
}
void remove(ll currl){
m[a[currl]]--;
if(m[a[currl]]==0)
ans--;
}
int main(int argc, char const *argv[])
{ ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n,i;
cin>>n;
bucket = (ll)sqrt(n);
for(i=0;i<n;i++){
cin>>a[i];
}
ll q,l,r;
cin>>q;
for(i=0;i<q;i++){
cin>>l>>r;
l--;r--;
vec.push_back(make_pair(i,make_pair(l,r)));
}
sort(vec.begin(),vec.end(),compar);
ll currl=0,currr=0;
for(i=0;i<vec.size();i++){
while(currl<vec[i].second.first){
remove(currl);
currl++;
}
while(currl>vec[i].second.first){
add(currl-1);
currl--;
}
while(currr<=vec[i].second.second){
add(currr);
currr++;
}
while(currr>vec[i].second.second+1){
remove(currr-1);
currr--;
}
final[vec[i].first] = ans;
}
for(i=0;i<q;i++){
cout<<final[i]<<endl;
}
return 0;
}