标签:
这道题额,对于每个点建一棵线段树,表示以它为左端点的所有区间……口胡不清。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <algorithm> 5 using namespace std; 6 const int maxn=200010; 7 int a[maxn],Hash[maxn],ok[maxn]; 8 int pre[maxn],nxt[maxn],head[maxn],fa[maxn],son[maxn]; 9 int sum[maxn*30],ch[maxn*30][2],rt[maxn],cnt; 10 void Insert(int pre,int &rt,int l,int r,int g,int d){ 11 rt=++cnt; 12 ch[rt][0]=ch[pre][0]; 13 ch[rt][1]=ch[pre][1]; 14 sum[rt]=sum[pre]+d; 15 if(l==r)return; 16 int mid=(l+r)>>1; 17 if(mid>=g)Insert(ch[pre][0],ch[rt][0],l,mid,g,d); 18 else Insert(ch[pre][1],ch[rt][1],mid+1,r,g,d); 19 } 20 21 int Query(int rt,int l,int r,int a,int b){ 22 if(l>=a&&r<=b)return sum[rt]; 23 int mid=(l+r)>>1,ret=0; 24 if(mid>=a)ret=Query(ch[rt][0],l,mid,a,b); 25 if(mid<b)ret+=Query(ch[rt][1],mid+1,r,a,b); 26 return ret; 27 } 28 void Init(){ 29 memset(rt,0,sizeof(rt)); 30 memset(head,0,sizeof(head)); 31 memset(pre,0,sizeof(pre)); 32 memset(son,0,sizeof(son)); 33 memset(nxt,0,sizeof(nxt)); 34 memset(fa,0,sizeof(fa)); 35 memset(sum,0,sizeof(sum)); 36 memset(ok,0,sizeof(ok));cnt=0; 37 } 38 int main(){ 39 int T,Q,n,l,r;a[0]=-1; 40 scanf("%d",&T); 41 while(T--){ 42 Init(); 43 scanf("%d",&n); 44 for(int i=1;i<=n;i++) 45 scanf("%d",&a[i]); 46 for(int i=1;i<=n;i++) 47 Hash[i]=a[i]; 48 sort(Hash+1,Hash+n+1); 49 for(int i=1;i<=n;i++) 50 a[i]=lower_bound(Hash+1,Hash+n+1,a[i])-Hash; 51 for(int i=2;i<n;i++) 52 if(a[i-1]<=a[i]&&a[i]<=a[i+1]) 53 ok[i]=1; 54 for(int i=1;i<=n;i++){ 55 pre[i]=head[a[i]]; 56 nxt[pre[i]]=i; 57 head[a[i]]=i; 58 } 59 for(int i=2;i<n;i++) 60 if(ok[i]){ 61 int j=pre[i]; 62 while(j&&(a[j-1]!=a[i-1]||a[j+1]!=a[i+1])){j=pre[j];} 63 fa[i]=j;son[j]=i; 64 } 65 for(int i=2;i<n;i++){ 66 if(!fa[i]&&ok[i]) 67 Insert(rt[1],rt[1],1,n,i,1); 68 } 69 70 for(int i=2;i<n;i++){ 71 if(!ok[i]){ 72 rt[i]=rt[i-1]; 73 continue; 74 } 75 Insert(rt[i-1],rt[i],1,n,i,-1); 76 if(son[i])Insert(rt[i],rt[i],1,n,son[i],1); 77 } 78 scanf("%d",&Q); 79 while(Q--){ 80 scanf("%d%d",&l,&r); 81 printf("%d\n",r-1>=l?Query(rt[l],1,n,1,r-1):0); 82 } 83 } 84 return 0; 85 }
数据结构(主席树):HDU 5654 xiaoxin and his watermelon candy
标签:
原文地址:http://www.cnblogs.com/TenderRun/p/5377083.html