Problem Description
很多學校流行一種比較的習慣。老師們很喜歡詢問,從某某到某某當中,分數最高的是多少。 這讓很多學生很反感。
不管你喜不喜歡,現在需要你做的是,就是按照老師的要求,寫一個程序,模擬老師的詢問。當然,老師有時候需要更新某位同學的成績。
Input
本題目包含多組測試,請處理到文件結束。 在每個測試的第一行,有兩個正整數 N 和 M ( 0<N<=200000,0<M<5000 ),分別代表學生的數目和操作的數目。 學生ID編號分別從1編到N。 第二行包含N個整數,代表這N個學生的初始成績,其中第i個數代表ID為i的學生的成績。 接下來有M行。每一行有一個字符 C (只取'Q'或'U') ,和兩個正整數A,B。 當C為'Q'的時候,表示這是一條詢問操作,它詢問ID從A到B(包括A,B)的學生當中,成績最高的是多少。 當C為'U'的時候,表示這是一條更新操作,要求把ID為A的學生的成績更改為B。
Output
對于每一次詢問操作,在一行里面輸出最高成績。
Sample Input
5 6
1 2 3 4 5
Q 1 5
U 3 6
Q 3 4
Q 4 5
U 2 9
Q 1 5
Sample Output
5
6
5
9
Build()O(n)
Update()O(logn)
Query()O(logn)
 CODE #include<iostream> #define MAX 700000 using namespace std; int st[200001]; struct Line { int l,r,max; }L[MAX]; int N,M; void Build(int s,int e,int step) { L[step].l=s; L[step].r=e; if(s==e) L[step].max=st[s]; else if(s<e) { int mid=(s+e)>>1; Build(s,mid,2*step); Build(mid+1,e,2*step+1); L[step].max=max(L[2*step].max,L[2*step+1].max); } return ; } int Up(int num,int val,int step) { if(L[step].l==L[step].r&&L[step].r==num) { L[step].max=val; } else if(L[step].l<L[step].r) { int mid=(L[step].l+L[step].r)>>1; if(num<=mid) Up(num,val,2*step); else Up(num,val,2*step+1); L[step].max=max(L[2*step].max,L[2*step+1].max); } return 0; } int Query(int s,int e,int step) { if(s==L[step].l&&e==L[step].r) return L[step].max; else if(L[step].l<L[step].r) { int mid=(L[step].l+L[step].r)>>1; if(e<=mid) return Query(s,e,2*step); else if(s>mid) return Query(s,e,2*step+1); else return max(Query(s,mid,2*step),Query(mid+1,e,2*step+1)); } } int main() { while(scanf("%d%d",&N,&M)!=EOF) { int i,j; for(i=1;i<=N;i++) scanf("%d",&st[i]); getchar(); char C; int a,b; Build(1,N,1); while(M--) { scanf("%c",&C); if(C=='Q') { scanf("%d%d",&a,&b); printf("%d\n",Query(a,b,1)); } else { scanf("%d%d",&a,&b); //st[a]=b; //Build(1,N,1); Up(a,b,1); } getchar(); } } system("pause"); return 0; }
|