2011-05-17 10:50:08 题目地址;http://poj.org/problem?id=3368 #include<iostream> #include<stdio.h> #define N 100010 using namespace std; struct Node { int l, r; }node[N]; struct SegNode { int l, r, c; SegNode *ls, *rs; }SN[N*2]; int count,flag[N]; int init(int n) { int i,j,now,before; scanf("%d",&before); node[1].l=1; flag[1]=1; for(i=2,j=1;i<=n;i++) { scanf("%d",&now); if(now!=before) { node[j].r=i; j++; node[j].l=i; before=now; } flag[i]=j; } node[j].r=i; return j; } SegNode* NewSN() { SN[count].ls=SN[count].rs=NULL; count++; return SN+(count-1); } SegNode* Build(int l,int r) { SegNode* root=NewSN(); root->l=l; root->r=r; if(l==r) { root->c=node[l].r-node[l].l; return root; } else { int mid=(l+r)>>1; root->ls=Build(l,mid); root->rs=Build(mid+1,r); root->c=root->ls->c>root->rs->c?root->ls->c:root->rs->c; return root; } } int Quiry(SegNode* root,int L,int R) { int mid=(root->l+root->r)>>1; //cout<<(root->l)<<" "<<(root->r)<<endl; if(L<=root->l&&R>=root->r) return root->c; if(L>mid) return Quiry(root->rs,L,R); if(R<=mid) return Quiry(root->ls,L,R); else { int x=Quiry(root->rs,L,R); int y=Quiry(root->ls,L,R); return x>y?x:y; } } int main() { int n,m,nn,a,b,res; SegNode *root; while (~scanf("%d",&n)&&n) { scanf("%d",&m); nn=init(n);// cout<<nn<<endl; count=0; root=Build(1,nn); while (m--) { scanf("%d%d",&a,&b); //cout<<flag[a]<<" "<<flag[b]<<endl; if(flag[a]==flag[b]) { res=b-a+1; } else { int x,y,z; x=node[flag[a]].r-a; y=b-node[flag[b]].l+1; res=x>y?x:y; if(flag[b]-flag[a]>1) { z=Quiry(root,flag[a]+1,flag[b]-1); res=res>z?res:z; } } printf("%d/n",res); } } return 0; }