题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1754
线段树节点更新练习
第四棵线段树……TUT……初始化的时候忘了把cnt设为0, RE了几次……=3=
1 #include <cstdio> 2 #include <cstring> 3 4 const int MAXN = 200000 + 10; 5 6 struct Node 7 { 8 int r, l; 9 int max; 10 Node *l_child, *r_child; 11 }; 12 13 Node Tree[MAXN + MAXN]; 14 int N, M; 15 int cnt; 16 17 int GetMax( int a, int b ) 18 { 19 return a > b ? a : b; 20 } 21 22 void BuildTree( int l, int r, Node *Td ) 23 { 24 Td->l = l; 25 Td->r = r; 26 if ( l == r ) 27 { 28 scanf( "%d", &Td->max ); 29 return; 30 } 31 32 ++cnt; 33 Td->l_child = Tree + cnt; 34 BuildTree( l, (l + r) / 2, Td->l_child ); 35 36 ++cnt; 37 Td->r_child = Tree + cnt; 38 BuildTree( (l + r) / 2 + 1, r, Td->r_child ); 39 40 Td->max = GetMax( Td -> l_child -> max, Td -> r_child -> max ); 41 42 return; 43 } 44 45 void Update( int ii, int &e, Node *Td ) 46 { 47 if ( ii == Td -> l && ii == Td -> r ) 48 { 49 Td -> max = e; 50 return; 51 } 52 53 if ( ii <= ( Td -> l + Td -> r ) / 2 ) 54 Update( ii, e, Td -> l_child ); 55 else if ( ii > ( Td -> l + Td -> r ) / 2 ) Update( ii, e, Td -> r_child ); 56 57 Td->max = GetMax( Td -> l_child -> max, Td -> r_child -> max ); 58 59 return; 60 } 61 62 int Query( int l, int r, Node *Td ) 63 { 64 if ( l == Td -> l && r == Td -> r ) 65 return Td -> max; 66 67 if ( r <= ( Td -> l + Td -> r ) / 2 ) return Query( l, r, Td -> l_child ); 68 else if ( l > ( Td -> l + Td -> r ) / 2 ) return Query( l, r, Td -> r_child ); 69 else return GetMax( Query( l, ( Td -> l + Td -> r ) / 2, Td -> l_child ), Query( ( Td -> l + Td -> r ) / 2 + 1, r, Td -> r_child ) ); 70 } 71 72 int main() 73 { 74 char op[4]; 75 while ( scanf( "%d%d", &N, &M ) != EOF ) 76 { 77 cnt = 0; 78 BuildTree( 1, N, Tree ); 79 for ( int i = 0; i < M; ++i ) 80 { 81 int a, b; 82 scanf( "%s%d%d", op, &a, &b ); 83 switch( op[0] ) 84 { 85 case 'Q': 86 printf( "%d\n", Query( a, b, Tree ) ); 87 break; 88 89 case 'U': 90 Update( a, b, Tree ); 91 break; 92 } 93 } 94 } 95 return 0; 96 }