This problem can be solve in simpler O(NsqrtN) solution, but I will describe O(NlogN) one.
We will solve this problem in offline. For each x (0?≤?x?<?n) we
should keep all the queries that end in x. Iterate that x from
0 to n?-?1. Also we need to keep some array D such
that for current x Dl?+?Dl?+?1?+?...?+?Dx will
be the answer for query [l;x]. To keep D correct,
before the processing all queries that end in x, we need to update D.
Let t be the current integer in A,
i. e. Ax,
and vector P be the list of indices of previous occurences of t (0-based
numeration of vector). Then, if |P|?≥?t, you need to add 1 to DP[|P|?-?t],
because this position is now the first (from right) that contains exactly t occurences
of t. After that, if |P|?>?t,
you need to subtract 2 from DP[|P|?-?t?-?1],
in order to close current interval and cancel previous. Finally, if |P|?>?t?+?1, then you need additionally add 1 to DP[|P|?-?t?-?2] to
cancel previous close of the interval.
#include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <iostream> #include <iomanip> #include <cmath> #include <map> #include <set> #include <queue> using namespace std; #define ls(rt) rt*2 #define rs(rt) rt*2+1 #define ll long long #define ull unsigned long long #define rep(i,s,e) for(int i=s;i<e;i++) #define repe(i,s,e) for(int i=s;i<=e;i++) #define CL(a,b) memset(a,b,sizeof(a)) #define IN(s) freopen(s,"r",stdin) #define OUT(s) freopen(s,"w",stdout) const int MAXN = 1e5+100; int n,m; int a[MAXN],c[MAXN],ans[MAXN]; struct Query { int l,r,id; bool operator < (const Query &t) const {return r<t.r;} }q[MAXN]; inline int lowbit(int x){return x&(-x);} void add(int i, int v) { while(i<=n) { c[i]+=v; i+=lowbit(i); } } int sum(int x) { int ret=0; while(x>0) { ret+=c[x]; x-=lowbit(x); } return ret; } int main() { int sz; while(~scanf("%d%d",&n,&m)) { vector<int>data[MAXN]; CL(c,0); for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<=m;i++) { scanf("%d%d",&q[i].l,&q[i].r); q[i].id=i; } sort(q+1,q+1+m); for(int i=1,k=1;i<=n;i++) { if(a[i]<=n) { data[a[i]].push_back(i); sz=data[a[i]].size(); if(sz>=a[i]) { add(data[a[i]][sz-a[i]],1); if(sz>a[i])add(data[a[i]][sz-a[i]-1],-2); if(sz>a[i]+1)add(data[a[i]][sz-a[i]-2],1); } } while(q[k].r==i && k<=m) { ans[q[k].id]=sum(q[k].r)-sum(q[k].l-1); k++; } } for(int i=1;i<=m;i++) printf("%d\n",ans[i]); } return 0; }
Codeforces 220B - Little Elephant and Array 离线树状数组,布布扣,bubuko.com