HDU-1754 I Hate It(線段樹,區間最大值)
阿新 • • 發佈:2019-01-01
很多學校流行一種比較的習慣。老師們很喜歡詢問,從某某到某某當中,分數最高的是多少。
這讓很多學生很反感。
不管你喜不喜歡,現在需要你做的是,就是按照老師的要求,寫一個程式,模擬老師的詢問。當然,老師有時候需要更新某位同學的成績。 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
Sample Output
這讓很多學生很反感。
不管你喜不喜歡,現在需要你做的是,就是按照老師的要求,寫一個程式,模擬老師的詢問。當然,老師有時候需要更新某位同學的成績。 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
5 6 5 9直接用線段樹求區間最小值即可
程式碼:
zkw線段樹:#include #include #include using namespace std; #define lson l, m, rt<<1 #define rson m+1, r, rt<<1|1 const int N = 200000 + 5; int T[N<<2]; void PushUP(int rt){ T[rt] = max(T[rt<<1], T[rt<<1|1]); } void Build(int l, int r, int rt){ if(l == r){ scanf("%d",&T[rt]); return ; } int m = (l + r) >> 1; Build(lson); Build(rson); PushUP(rt); } void Updata(int p, int v, int l, int r, int rt){ if(l == r){ T[rt] = v; return ; } int m = (l + r) >> 1; if(p <= m) Updata(p, v, lson); else Updata(p, v, rson); PushUP(rt); } int Query(int L, int R, int l, int r, int rt){ if(L <= l && r<= R) return T[rt]; int m = (l + r) >> 1; int ret = 0; if(L <= m) ret = max(ret, Query(L, R, lson)); if(R > m) ret = max(ret, Query(L, R, rson)); return ret; } int main(){ char ch[3]; int n, m, a, b; while(scanf("%d %d", &n, &m)==2){ Build(1, n, 1); for(int i = 1; i <= m; i++){ scanf("%s %d %d", ch, &a, &b); if(ch[0] == 'Q') printf("%d\n", Query(a, b, 1, n, 1)); else Updata(a, b, 1, n, 1); } } return 0; }
#include #include #include using namespace std; #define lson l, m, rt<<1 #define rson m+1, r, rt<<1|1 const int N = 200000 + 5; int T[N<<2],M; void Build(int n){ for(M=1; M<=n+1; M*=2); for(int i=M+1; i<=M+n; i++) scanf("%d",&T[i]); for(int i=M-1; i ;i--) T[i] = max(T[i<<1], T[i<<1|1]); } void Updata(int n,int V){ for(T[n+=M]=V, n/=2; n; n/=2) T[n] = max(T[n<<1], T[n<<1|1]); } int Query(int s, int t){ int maxc = 0; for(s=s+M-1, t=t+M+1; s^t^1; s/=2,t/=2){ if(~s&1) maxc = max(maxc, T[s^1]); if(t&1) maxc = max(maxc, T[t^1]); } return maxc; } int main(){ char ch[3]; int n, m, a, b; while(scanf("%d %d", &n, &m)==2){ Build(n); for(int i = 1; i <= m; i++){ scanf("%s %d %d", ch, &a, &b); if(ch[0] == 'Q') printf("%d\n", Query(a, b)); else Updata(a, b); } } return 0; }