HDU1540 Turnal Warfare
线段树保存每个区间的左边最大连续长度和右边最大连续长度~
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> using namespace std; const int maxn=1e6+14; struct node { int l,r; int ll,rl,ml; //左边开始连续的最大长度和右边开始连续的最大长度 //以及这个区间的最大连续长度 }segTree[maxn*4]; void build (int i,int l,int r) { segTree[i].l=l; segTree[i].r=r; segTree[i].ll=segTree[i].rl=segTree[i].ml=r-l+1; if (l==r) return; int mid=(l+r)>>1; build (i<<1,l,mid); build (i<<1|1,mid+1,r); } void update (int i,int t,int val) { if (segTree[i].l==segTree[i].r) { if (val==1) segTree[i].ll=segTree[i].rl=segTree[i].ml=1; else segTree[i].ll=segTree[i].rl=segTree[i].ml=0; return; } int mid=(segTree[i].l+segTree[i].r)>>1; if (t<=mid) update (i<<1,t,val); else update (i<<1|1,t,val); segTree[i].ll=segTree[i<<1].ll; segTree[i].rl=segTree[i<<1|1].rl; segTree[i].ml=max(segTree[i<<1].ml,segTree[i<<1|1].ml); segTree[i].ml=max(segTree[i].ml,segTree[i<<1].rl+segTree[i<<1|1].ll); if (segTree[i<<1].ll==segTree[i<<1].r-segTree[i<<1].l+1) segTree[i].ll+=segTree[i<<1|1].ll; if (segTree[i<<1|1].rl==segTree[i<<1|1].r-segTree[i<<1|1].l+1) segTree[i].rl+=segTree[i<<1].rl; } int query (int i,int t) { if (segTree[i].l==segTree[i].r||segTree[i].ml==0||segTree[i].ml==segTree[i].r-segTree[i].l+1) return segTree[i].ml; int mid=(segTree[i].l+segTree[i].r)>>1; if (t<=mid) { if (t>=segTree[i<<1].r-segTree[i<<1].rl+1) return query (i<<1,t)+query (i<<1|1,mid+1); else return query (i<<1,t); } else { if (t<=segTree[i<<1|1].l+segTree[i<<1|1].ll-1) return query (i<<1|1,t)+query(i<<1,mid); else return query (i<<1|1,t); } } int a[maxn],top,n,m,x; string s; int main () { while (~scanf ("%d %d",&n,&m)) { build (1,1,n); top=0; while (m--) { cin>>s; if (s=="D") { scanf ("%d",&x); a[top++]=x; update (1,x,0); } else if (s=="Q") { scanf ("%d",&x); printf ("%d\n",query(1,x)); } else { if (x>0) { x=a[--top]; update (1,x,1); } } } } return 0; }