杭電 HDU ACM 1754 I Hate It (線段樹)
阿新 • • 發佈:2019-01-29
I Hate It
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 47272 Accepted Submission(s): 18507
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 Hint
Author
linle
暈死…………這個是自己手寫的第一個線段樹,我希望有一天,能沒必要用模版!一大早上終於bug挑完了!一開始很多邏輯錯誤,按著對線段樹原理的理解,不段修正程式碼,在這個過程中加深了對線段樹的理解,不過有一個 非常無聊但很重要的bug!~小心讀取字元或著字串的時候,緩衝區還存在換行符!!!!!!!
另外對於線段樹 這種大量資料的操作切記不要用cin cout物件讀取!
#include<iostream> #include<sstream> #include<algorithm> #include<cstdio> #include<string.h> #include<cctype> #include<string> #include<cmath> #include<vector> #include<stack> #include<queue> #include<map> #include<set> using namespace std; const int INF=200003; int val[INF]; struct Tree { int left,right,Max; } tree[INF<<2]; int create(int root,int left,int right) { tree[root].left=left; tree[root].right=right; if(left==right) { return tree[root].Max=val[left]; } int a,b,middle=(left+right)>>1; a=create(root<<1,left,middle); b=create(root<<1|1,middle+1,right); return tree[root].Max=max(a,b); } int cal(int root,int left,int right) { if(tree[root].left>right||tree[root].right<left) return 0; if(tree[root].left>=left&&tree[root].right<=right) { return tree[root].Max; } int a,b,mid=(tree[root].left+tree[root].right)>>1; a=cal(root<<1,left,right); b=cal(root<<1|1,left,right); return max(a,b); } void update(int root,int pos,int val) { if(tree[root].left==tree[root].right) { //cout<<"lianghus"<<"root="<<root<<" "<<tree[root].left<<endl; tree[root].Max=val; return; } int mid=(tree[root].left+tree[root].right)>>1; if(pos<=mid) { update(root<<1,pos,val); } else update(root<<1|1,pos,val); tree[root].Max=max(tree[root<<1].Max,tree[root<<1|1].Max); } int main() { int n,m; while(scanf("%d%d",&n,&m)!=EOF) { memset(val,0,sizeof(val)); for(int i=1; i<=n; i++) { scanf("%d",&val[i]); } create(1,1,n); getchar(); for(int i=0; i<m; i++) { char ch; scanf("%c",&ch); if(ch=='Q') { int a,b; scanf("%d%d",&a,&b); getchar(); printf("%d\n",cal(1,a,b)); } else if(ch=='U') { int a,b; scanf("%d%d",&a,&b); getchar(); update(1,a,b); } } } return 0; }