Line Segment tree
Question:
The question is how many consecutive segments can be composed of numbers in a range. First, consider adding a number from left to right. Considering that the answer to the number of I-1 is X, what is the answer after I is added? It can be seen that it depends on whether a [I]-1 and a [I] + 1 have been added, if a [I]-1 or a [I] + 1 has been added, the number of segments remains unchanged. If not, the number of segments is added to 1, if both are added, the number of segments is reduced by 1. Set V [I] to the number of changes after I is added, the number of segments added to the X number is sum {v [I]} (1 <= I <= x }. Think about it. If you delete a number, the change of the number at both ends of the number will also change. In this way, the number of segments in a certain range will be the sum of their v values. Offline query processing will be performed, sorted by left endpoint, scanned again, deleted on the left, inserted on the right, query is the interval and sum.
//1109MS 7296K #include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define ls (rt<<1)#define rs (rt<<1|1)#define mid ((t[rt].l+t[rt].r)>>1)#define maxn 200010int num[maxn];int vis[maxn];int pla[maxn];int n,m;struct que{int l,r;int id;int ans;}q[maxn];struct tree{int l,r;int sum;}t[maxn<<2];bool cmp(que &a,que &b){return a.l<b.l;}bool cmp1(que &a,que &b){return a.id<b.id;}void pushup(int rt){t[rt].sum=t[ls].sum+t[rs].sum;}int query(int rt,int l,int r){if(t[rt].l==l&&t[rt].r==r)return t[rt].sum;if(r<=mid)return query(ls,l,r);else if(l>mid)return query(rs,l,r);else return query(ls,l,mid)+query(rs,mid+1,r);}void change(int rt,int l,int r,int val){if(t[rt].l==l&&t[rt].r==r){t[rt].sum=val;return;}if(r<=mid)change(ls,l,r,val);else if(l>mid)change(rs,l,r,val);else{change(ls,l,mid,val);change(rs,mid+1,r,val);}pushup(rt);}void build(int rt,int l,int r){t[rt].l=l,t[rt].r=r;t[rt].sum=0;if(l==r)return ;build(ls,l,mid);build(rs,mid+1,r);}int main(){int T;int i,j;int a,b,k;cin>>T;while(T--){scanf("%d%d",&n,&m);memset(vis,0,sizeof(vis));memset(pla,0,sizeof(pla));memset(num,0,sizeof(num));build(1,1,n);for(i=1;i<=n;i++){scanf("%d",&num[i]);if(!vis[num[i]-1]&&!vis[num[i]+1])change(1,i,i,1);else if(vis[num[i]-1]&&vis[num[i]+1])change(1,i,i,-1);pla[num[i]]=i;vis[num[i]]=1;}for(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);q[0].l=1;for(i=1;i<=m;i++){for(j=q[i-1].l;j<=q[i].l-1;j++){vis[num[j]]=0;a=pla[num[j]+1];if(num[j]+1<=n&&a>=q[i].l){k=query(1,a,a);if(k==-1)change(1,a,a,0);else if(k==0)change(1,a,a,1);}b=pla[num[j]-1];if(num[j]-1>=1&&b>=q[i].l){k=query(1,b,b);if(k==-1)change(1,b,b,0);else if(k==0)change(1,b,b,1);}}q[i].ans=query(1,q[i].l,q[i].r);}sort(q+1,q+m+1,cmp1);for(int i=1;i<=m;i++)printf("%d\n",q[i].ans);}return 0;}