Problem Description
很多學(xué)校流行一種比較的習(xí)慣。老師們很喜歡詢問,從某某到某某當(dāng)中,分?jǐn)?shù)最高的是多少。 這讓很多學(xué)生很反感。
不管你喜不喜歡,現(xiàn)在需要你做的是,就是按照老師的要求,寫一個(gè)程序,模擬老師的詢問。當(dāng)然,老師有時(shí)候需要更新某位同學(xué)的成績。
Input
本題目包含多組測試,請?zhí)幚淼轿募Y(jié)束。 在每個(gè)測試的第一行,有兩個(gè)正整數(shù) N 和 M ( 0<N<=200000,0<M<5000 ),分別代表學(xué)生的數(shù)目和操作的數(shù)目。 學(xué)生ID編號分別從1編到N。 第二行包含N個(gè)整數(shù),代表這N個(gè)學(xué)生的初始成績,其中第i個(gè)數(shù)代表ID為i的學(xué)生的成績。 接下來有M行。每一行有一個(gè)字符 C (只取'Q'或'U') ,和兩個(gè)正整數(shù)A,B。 當(dāng)C為'Q'的時(shí)候,表示這是一條詢問操作,它詢問ID從A到B(包括A,B)的學(xué)生當(dāng)中,成績最高的是多少。 當(dāng)C為'U'的時(shí)候,表示這是一條更新操作,要求把ID為A的學(xué)生的成績更改為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; }
|