题目链接:http://codeforces.com/problemset/problem/220/B
题目大意:
给定一个长度为n(1<=n<=10000)的数组a[],有m次(1<=m<=10000)询问l,r(表示[l,r]内,有几个数出现的次数恰好等于本身的数值).
题目思路:
对询问离线处理,按照r排序.
对a从1~n,顺序处理.
设number[x],为x出现的次数,position[x][y]为x出现第y次的位置.
设在i位置时,number[ a[i] ] >= a[i]
则第 position[ a[i] ][ number[ a[i] ] - a[i] + 1] 的值设为 1,
第 position[ a[i] ][ number[ a[i] ] - a[i] ] 的值设为-1.
这样处理到i时,如果有query[j].r==i时,
则result[ query[j].id ] =sum[ query[j].r ] - sum[ query[j].l -1 ].
代码:
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <math.h> #include <stack> #include <queue> #include <map> #include <set> #include <vector> #include <string> #include <iostream> #include <algorithm> using namespace std; #define ll long long #define ls rt<<1 #define rs ls|1 #define lson l,mid,ls #define rson mid+1,r,rs #define middle (l+r)>>1 #define eps (1e-9) #define type int #define clr_all(x,c) memset(x,c,sizeof(x)) #define clr(x,c,n) memset(x,c,sizeof(x[0])*(n+1)) #define MOD 1000000007 #define inf 0x3f3f3f3f #define pi acos(-1.0) template <class T> void _swap(T &x,T &y){T t=x;x=y;y=t;} template <class T> T _max(T x,T y){return x>y? x:y;} template <class T> T _min(T x,T y){return x<y? x:y;} int test,cas; const int M=100000 +5; int n,m; int a[M],val[M],ans[M]; vector<int>pos[M]; struct qry{ int id,l,r; bool operator < (const qry &t) const { return r < t.r; } }q[M]; void update(int x,int c){ for(;x<=n+1;x+=(x&-x)) val[x]+=c; } int query(int x){ int res=0; for(;x>0;x-=(x&-x)) res+=val[x]; return res; } void run(){ int i,j; for(i=1;i<=n;i++) scanf("%d",&a[i]); for(i=1;i<=m;i++){ scanf("%d%d",&q[i].l,&q[i].r); q[i].id=i; } sort(q+1,q+m+1); clr(val,0,n+1); for(i=j=1;i<=n && j<=m;i++){ if(a[i]<=n){ pos[a[i]].push_back(i); int sz=pos[a[i]].size(); if(sz>=a[i]){ update(pos[a[i]][sz-a[i]]+1,1); if(sz-a[i]>0){ update(pos[a[i]][sz-a[i]-1]+1,-2); if(sz-a[i]>1) update(pos[a[i]][sz-a[i]-2]+1,1); } } } while(j<=m && i==q[j].r){ ans[q[j].id]=query(q[j].r+1)-query(q[j].l); j++; } } for(i=1;i<=m;i++) printf("%d\n",ans[i]); for(i=1;i<=n;i++) if(a[i]<=n){ if(!pos[a[i]].size()) continue; pos[a[i]].clear(); } } void preSof(){ } int main(){ //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); preSof(); //run(); while(scanf("%d%d",&n,&m)!=EOF) run(); //for(scanf("%d",&test),cas=1;cas<=test;cas++) run(); return 0; }