1 5 2 3 1 2 5 4 1 5 2 4
1 2
题解:莫队算法+分块
脑残错误害死人啊。
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #define N 100003 using namespace std; int n,m,t; int ans1[N],num[N],b[N],p[N],vis[N],belong[N],a[N]; struct data { int l,r,num; }; data a1[N]; int cmp1(data a,data b) { if (belong[a.l]==belong[b.l]) return a.r<b.r; return belong[a.l]<belong[b.l]; } int main() { scanf("%d",&t); for (int k=1;k<=t;k++) { scanf("%d%d",&n,&m); for (int i=1;i<=n;i++) scanf("%d",&a[i]); for (int i=1;i<=m;i++) scanf("%d%d",&a1[i].l,&a1[i].r),a1[i].num=i; int size=ceil(sqrt(n)); for (int i=1;i<=n;i++) belong[i]=(i-1)/size+1; sort(a1+1,a1+m+1,cmp1); memset(vis,0,sizeof(vis)); memset(ans1,0,sizeof(ans1)); int l=1; int r=0; int ans=0; for (int i=1;i<=m;i++) { while (r<a1[i].r) { r++; vis[a[r]]=1; if (vis[a[r]-1]&&vis[a[r]+1]) ans--; if (!vis[a[r]-1]&&!vis[a[r]+1]) ans++; } while (r>a1[i].r) { vis[a[r]]=0; if (vis[a[r]-1]&&vis[a[r]+1]) ans++; if (!vis[a[r]-1]&&!vis[a[r]+1]) ans--; r--; } while (l>a1[i].l) { l--; if (vis[a[l]-1]&&vis[a[l]+1]) ans--; if (!vis[a[l]-1]&&!vis[a[l]+1]) ans++; vis[a[l]]=1; } while (l<a1[i].l) { vis[a[l]]=0; if (vis[a[l]-1]&&vis[a[l]+1]) ans++; if (!vis[a[l]-1]&&!vis[a[l]+1]) ans--; l++; } ans1[a1[i].num]=ans; } for (int i=1;i<=m;i++) printf("%d\n",ans1[i]); } }