1 #include <stdio.h> 2 #include <string.h> 3 #include <math.h> 4 #include <algorithm> 5 #include <iostream> 6 #include <ctype.h> 7 #include <iomanip> 8 #include <queue> 9 #include <stdlib.h> 10 11 using namespace std; 12 13 const int maxn = 200000 + 10, INF = -214748364; 14 int a[maxn], b[4*maxn], A, B; //a为输入数组,maxv为线段树结点数组,存该相应区间的最大值 15 16 void update(int o, int L, int R) //线段树更新,把a[A]改为B 17 { 18 if(L == R) 19 b[o] = B; 20 else 21 { 22 int M = L + (R - L) / 2; 23 if(A <= M) 24 update(2*o, L, M); 25 else 26 update(2*o+1, M+1, R); 27 b[o] = max(b[2*o], b[2*o+1]); 28 } 29 } 30 31 int query(int o, int L, int R) //线段树查询[A, B]间的最大值 32 { 33 if(A <= L && R <= B) 34 return b[o]; 35 int M = L + (R - L) / 2, ans = INF; 36 if(A <= M) 37 ans = max(ans, query(2*o, L, M)); 38 if(B > M) 39 ans = max(ans, query(2*o+1, M+1, R)); 40 return ans; 41 } 42 43 void build(int o, int L, int R) //建树 44 { 45 46 if(L == R) 47 { 48 b[o] = a[L]; 49 return; 50 } 51 int M = L + (R - L) / 2; 52 if(L <= M) 53 build(2*o, L, M); 54 if(R > M) 55 build(2*o+1, M+1, R); 56 b[o]=max(b[2*o], b[2*o+1]); 57 58 } 59 int main() 60 { 61 int N, M; 62 char c; 63 while(~scanf("%d%d\n", &N, &M)) 64 { 65 for(int i = 1; i <= N; i++) scanf("%d", &a[i]); 66 build(1, 1, N); 67 /*for (int i = 1; i <= 2*N; ++i) 68 { 69 printf("%d\n",b[i]); //5 3 5 2 3 4 5 1 2 70 }*/ 71 while(M--) 72 { 73 scanf("\n%c%d%d", &c, &A, &B); 74 if(c == ‘U‘){ 75 update(1, 1, N); 76 /*for (int i = 1; i <= 2*N; ++i) 77 { 78 printf("%d\n",b[i]); //6 6 5 2 6 4 5 1 2 79 }*/ 80 } 81 else printf("%d\n", query(1, 1, N)); 82 } 83 } 84 return 0; 85 }
原文:http://www.cnblogs.com/wangmengmeng/p/4986383.html