题目链接:http://codeforces.com/problemset/problem/220/B
题目大意:给定一个含有 n 个元素序列,给定 m 个区间,求每个区间内 x出现的个数等于 x 的数的个数;
思路:离散化+莫队,本来我用map 做标记,但是TLE了,因为 mp 复杂度好像是 log;
#include<cstring>
#include<cstdio>
#include<string>
#include<algorithm>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const double PI=acos(-1.0);
const int mod=1e9;
const int N=1e5+10;
int pos[N],ans[N];
int a[N];//存离散化后的序列
int b[N];//存离散化前的序列
int flag[N];
int vis[N];
int res;
struct mmp//用在离散化
{
int a,id;
}num[N];
bool cmpe(mmp x,mmp y)
{
if(x.a!=y.a)
return x.a<y.a;
return x.id<y.id;
}
struct node
{
int l,r,id;
} q[N];
bool cmp(node x,node y)
{
if(pos[x.l]==pos[y.l])
return x.r<y.r;
return pos[x.l]<pos[y.l];
}
void add(int x)
{
flag[a[x]]++;
if(flag[a[x]]==b[x])//这里比较的时候要和原来的数值比较
{
res++;
vis[a[x]]++;
}
else
{
if(vis[a[x]]==1)
{
vis[a[x]]=0;
res--;
}
}
}
void del(int x)
{
flag[a[x]]--;
if(flag[a[x]]==b[x]&&flag[a[x]]>0)//同上
{
res++;
vis[a[x]]++;
}
else
{
if(vis[a[x]]==1)
{
vis[a[x]]=0;
res--;
}
}
}
int main()
{
// freopen("E:\\in1.text","r",stdin);
// freopen("E:\\out0.text","w",stdout);
res=0;
int n,m;
scanf("%d %d",&n,&m);
int sz=sqrt(n);
for(int i=1; i<=n; i++)
{
scanf("%d",&num[i].a);
num[i].id=i;
b[i]=num[i].a;
pos[i]=i/sz;
}
sort(num+1,num+1+n,cmpe);
int cut=1;
a[num[1].id]=cut;
for(int i=2;i<=n;i++)
{
if(num[i].a!=num[i-1].a)
cut++;
a[num[i].id]=cut;
}
for(int i=1; i<=m; i++)
{
scanf("%d %d",&q[i].l,&q[i].r);
q[i].id=i;
}
sort(q+1,q+m+1,cmp);
int L=1,R=0;
for(int i=1; i<=m; i++)
{
while(R<q[i].r)
{
R++;
add(R);
}
while(L>q[i].l)
{
L--;
add(L);
}
while(L<q[i].l)
{
del(L);
L++;
}
while(R>q[i].r)
{
del(R);
R--;
}
ans[q[i].id]=res;
}
for(int i=1; i<=m; i++) printf("%d\n",ans[i]);
return 0;
}