题目链接:
http://codeforces.com/problemset/problem/220/B
题意:
给你一个 n n n个元素的序列 a a a,给你一些查询 [ l i , r i ] [l_i,r_i] [li,ri],问你在 l i l_i li和 r i r_i ri之间的 a [ x ] a[x] a[x]的个数, a [ x ] a[x] a[x]在这个区间里出现的个数等于 a [ x ] a[x] a[x]即它本身,要你对于每个询问输出 a [ x ] a[x] a[x]的个数;
分析:
莫队,看代码吧,关键就是对于移动指针的过程中的修改操作了;
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define inf 0x7f7f7f7f
#define maxn 100090
#define N 2
#define mod 100003
typedef long long ll;
typedef struct {
int u, v, next, w;
} Edge;
Edge e[N];
int cnt, head[N];
inline void add1(int u, int v) {
e[cnt].u = u;
e[cnt].v = v;
//e[cnt].w=w;
// e[cnt].f=f;
e[cnt].next = head[u];
head[u] = cnt++;
//e[cnt].u=v;
// e[cnt].v=u;
// e[cnt].w=0;
// e[cnt].f=-f;
// e[cnt].next=head[v];
// head[v]=cnt++;
}
inline void write(int x) {
if (x < 0)
putchar('-'), x = -x;
if (x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x * f;
}
int res,n,m,ans[maxn],pos[maxn],a[maxn],cot[maxn];
struct node{
int l,r,id;
}p[maxn];
bool com(node a,node b){
if(pos[a.l]==pos[b.l])return a.r<b.r;
else return pos[a.l]<pos[b.l];
}
inline void add(int x){//增加是先移动,再修改
if(a[x]>maxn)return ;
if(cot[a[x]]==a[x])res--;
else if(cot[a[x]]+1==a[x])res++;
cot[a[x]]++;
}
inline void del(int x){//删除是先修改,再移动
if(a[x]>maxn)return ;
if(cot[a[x]]==a[x])res--;
else if(cot[a[x]]-1==a[x])res++;
cot[a[x]]--;
}
int main() {
scanf("%d%d",&n,&m);
int sz=sqrt(n);
for(int i=1;i<=n;i++) {
scanf("%d", &a[i]);
pos[i] = i / sz;
}
for(int i=1;i<=m;i++){
scanf("%d%d",&p[i].l,&p[i].r);
p[i].id=i;
}
sort(p+1,p+1+m,com);
int l=1,r=0;
for(int i=1;i<=m;i++){
while(r<p[i].r){
r++;
add(r);
}
while(l>p[i].l){
l--;
add(l);
}
while(r>p[i].r){
del(r);
r--;
}
while(l<p[i].l){
del(l);
l++;
}
ans[p[i].id]=res;
}
for(int i=1;i<=m;i++)
printf("%d\n",ans[i]);
return 0;
}
我们坚持一件事情,并不是因为这样做了会有效果,而是坚信,这样做是对的。
——哈维尔