题意:
n个数,m次询问。值为x的人可以 和 值为 x-1,x+1 的人一组,求每次所给的区间内有多少组。
1 5 2 3 1 2 5 4 1 5 2 4
第一次询问中 1 2 3 4 5 一组
第二次询问中 1 2一组,5一组
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<bitset>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
struct node
{
int l,r,id;
}t[maxn];
int a[maxn];
int n,m,block;
int cnt[maxn],res[maxn],ans;
bool cmp(node a,node b){//按照奇偶性排序
if( (a.l/block)==(b.l/block) ){//当左端点位于同一个块时
if( (a.l/block)%2 )//左端点的块序号为奇数时
return a.r<b.r;//按照从小到大排
else//左端点的块序号为偶数时
return a.r>b.r;//按照从大到小排
}
else//当左端点不位于同一个块时
return a.l<b.l;//按照块的位置进行排序
//return (a.l/block)^(b.l/block) ? a.l<b.l : ( ((a.l/block)&1)?a.r<b.r:a.r>b.r );
}
void add(int x)
{
cnt[x] = 1;
if(cnt[x-1] && cnt[x+1])
ans--;
else if(!cnt[x-1] && !cnt[x+1])
ans++;
}
void del(int x)
{
cnt[x] = 0;
if(cnt[x-1] && cnt[x+1])
ans++;
else if(!cnt[x-1] && !cnt[x+1])
ans--;
}
int main()
{
int T;
int l,r;
scanf("%d",&T);
for(int k=1;k<=T;k++)
{
memset(cnt,0,sizeof(cnt));
scanf("%d%d",&n,&m);
block = sqrt(1.0*n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&t[i].l,&t[i].r);
t[i].id = i;
}
//printf("Case %d:\n",k);
sort(t+1,t+m+1,cmp);
l = t[1].l , r = t[1].l-1;
ans = 0;
for(int i=1;i<=m;i++)
{ //范围先扩大后缩小
while(l>t[i].l) add(a[--l]);
while(r<t[i].r) add(a[++r]);
while(l<t[i].l) del(a[l++]);
while(r>t[i].r) del(a[r--]);
res[t[i].id] = ans;
}
for(int i=1;i<=m;i++)
printf("%d\n",res[i]);
}
return 0;
}