跟hdu4630如出一辙,但是思想上还是要有特别技巧
对于[l,r]上的数a[i],我们给一个标记mark[i],表示第第i个数属于某个连续区间
初始时都赋值为0
pos[a[i]] 表示值为a[i]的数所在位置
当遇到情况 a[i]+1 或 a[i]-1 曾经 出现过时,mark[ pos[a[i]-1] ] = 1 或 mark[ pos[a[i]+1] ] = 1
最终结果 = (r-l+1) - sum(mark[l...r])
可以用线段树来储存mark[],维护sum
但这种算法的正确性来源于我们从左到右递推,而询问不会从左到右这么巧
所以我们要离线
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
#include <map>
using namespace std;
#define INF 1e9
#define maxn 100010
#define rep(i,x,y) for(int i=x;i<=y;i++)
#define mset(x) memset(x,0,sizeof(x))
const int maxnode = 100010*4;
int x, x1, x2, res;
struct IntervalTree{
int sumv[maxnode];
void init(){ mset(sumv); }
void update(int o, int l, int r){
if(l==r){
sumv[o]++;
return ;
}
int mid = l+(r-l)/2, lc = 2*o, rc = 2*o+1;
if(x<=mid) update(lc, l, mid);
else update(rc, mid+1, r);
sumv[o] = sumv[lc] + sumv[rc];
}
void query(int o, int l, int r){
if(x1<=l && x2>=r){
res+=sumv[o];
return;
}
int mid = l+(r-l)/2, lc = 2*o, rc = 2*o+1;
if(x1<=mid) query(lc, l, mid);
if(x2>mid) query(rc, mid+1, r);
}
}tree;
int t, n, m;
int a[maxn];
struct operate{
int l, r, id;
bool operator< (const operate& c)const{
return r<c.r;
}
}op[maxn];
int ans[maxn];
int pos[maxn];
int main(){
// freopen("a.txt","r",stdin);
// freopen(".out","w",stdout);
cin>>t;
while(t--){
cin>>n>>m;
rep(i,1,n) scanf("%d", &a[i]);
rep(i,1,m){
scanf("%d%d", &op[i].l, &op[i].r);
op[i].id = i;
}
sort(op+1, op+m+1);
memset(pos, -1, sizeof(pos));
tree.init();
int qcnt=1;
rep(i,1,n){
if( pos[a[i]-1]>=0 ){
x = pos[a[i]-1];
tree.update(1,1,n);
}
if( pos[a[i]+1]>=0 ){
x = pos[a[i]+1];
tree.update(1,1,n);
}
while(qcnt<=m && op[qcnt].r==i){
x1 = op[qcnt].l, x2 = op[qcnt].r;
res = 0;
tree.query(1,1,n);
ans[op[qcnt].id] = (x2 - x1 + 1) - res;
qcnt++;
}
if(qcnt>m) break;
pos[a[i]] = i;
}
rep(i,1,m) printf("%d\n", ans[i]);
}
return 0;
}