1. 程式人生 > >線段樹模板hdu 1754:I Hate It

線段樹模板hdu 1754:I Hate It

out sample ssi build sed splay align sub 一次

      I Hate It

Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 100523 Accepted Submission(s): 37845

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 Recommend lcy &nbsp| &nbspWe have carefully selected several similar problems for you: 1698 1542 1394 2795 1540

分析:此題為經典線段樹模板題, 標誌性的更新和查詢操作, 如果無數條更新和查詢操作時, 想到線段樹, 很可能就是一道與此題類似的線段樹題歐。。

ac代碼:

技術分享圖片
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 const int N=200000+50;
 7 struct tree{
 8     int l, r, maxn;
 9 };
10 tree t[N*3];
11 int ans;
12 
13 void build(int m, int l, int r)
14 {
15     t[m].l = l;
16     t[m].r = r;
17     if
(l==r) 18 { 19 scanf("%d", &t[m].maxn); 20 return; 21 } 22 int mid = (l + r) >> 1; 23 build(m<<1, l, mid); 24 build(m<<1|1, mid+1, r); 25 t[m].maxn = max(t[m<<1].maxn, t[m<<1|1].maxn); 26 } 27 void U(int m, int a, int b) 28 { 29
if(t[m].l == t[m].r && t[m].l == a) 30 { 31 t[m].maxn = b; 32 return; 33 } 34 int mid = (t[m].l + t[m].r) >> 1; 35 if(a <= mid) 36 U(m<<1, a, b); 37 else 38 U(m<<1|1, a, b); 39 t[m].maxn = max(t[m<<1].maxn, t[m<<1|1].maxn); 40 } 41 void Q(int m, int l, int r) 42 { 43 if(t[m].l == l && t[m].r == r) 44 { 45 ans = max(ans, t[m].maxn); 46 return; 47 } 48 int mid = (t[m].l + t[m].r) >> 1; 49 if(r <= mid) 50 Q(m<<1, l, r); 51 else if(l >= mid + 1) 52 Q(m<<1|1, l, r); 53 else 54 { 55 Q(m<<1, l, mid); 56 Q(m<<1|1, mid+1, r); 57 } 58 } 59 int main() 60 { 61 int n, m; 62 while(scanf("%d%d", &n, &m)!=EOF) 63 { 64 build(1, 1, n); 65 for(int i=0;i<m;i++) 66 { 67 getchar(); 68 char c; 69 int a, b; 70 scanf("%c", &c); 71 scanf("%d%d", &a, &b); 72 if(c == Q) 73 { 74 ans = 0; 75 Q(1, a, b); 76 printf("%d\n", ans); 77 } 78 else 79 U(1, a, b); 80 } 81 } 82 return 0; 83 }
View Code

線段樹模板hdu 1754:I Hate It