Shirlies
宁静专注认真的程序媛~

一道简单的线段树题目,好久没有刷题,偶来刷刷,除了刚开始提交RE了,原因是segtree数组开的太小了,一改大就A了,本来代码是用vim写的,用G++编译,结果老是报错,错的都很离谱,就改用code::blocks编译@_@。。。再去研究下G++。。。

代码如下:
  1 #include <cstdio>
  2 #include <algorithm>
  3 
  4 const int maxlen = 200000+10;
  5 int scores[maxlen];
  6 
  7 struct node
  8 {
  9     int left,right;
 10     int value;
 11     node(){}
 12     node(int l,int r,int v)
 13     {
 14         left = l;
 15     right = r;
 16     value = v;
 17     }
 18 };
 19 node segtree[10*maxlen];
 20 
 21 void build(int left,int right,int root)
 22 {
 23     if(left == right)
 24     {
 25     segtree[root] = node(left,right,scores[left]);
 26     return;
 27     }
 28 
 29     int mid = (left + right) >> 1;
 30     int lRoot = root << 1;
 31     build(left,mid,lRoot);
 32     build(mid + 1,right,lRoot+1);
 33     segtree[root] = node(left,right,std::max(segtree[lRoot].value,segtree[lRoot + 1].value));
 34 }
 35 
 36 void update(int left,int right,int s,int root,int value)
 37 {
 38     if(left == right)
 39     {
 40     segtree[root].value = value;
 41     return ;
 42     }
 43 
 44     int mid = (left + right) >> 1;
 45     int lRoot = root << 1;
 46     if(s <= mid)
 47     {
 48     update(left,mid,s,lRoot,value);
 49     segtree[root].value = std::max(segtree[lRoot+1].value,segtree[lRoot].value);
 50     }
 51     else
 52     {
 53         update(mid + 1,right,s,lRoot + 1,value);
 54         segtree[root].value = std::max(segtree[lRoot].value,segtree[lRoot+1].value);
 55     }
 56 }
 57 
 58 int query(int left,int right,int root,int l,int r)
 59 {
 60     if(l == left && r == right)
 61     {
 62     return segtree[root].value;
 63     }
 64 
 65     int mid = (left + right) >> 1;
 66     int lRoot = root << 1;
 67     int maxvalue = 0;
 68     int v;
 69 
 70     if(r <= mid)
 71     {
 72     v = query(left,mid,lRoot,l,r);
 73     maxvalue = std::max(maxvalue,v);
 74     }else if(l > mid)
 75     {
 76     v = query(mid+1,right,lRoot+1,l,r);
 77     maxvalue = std::max(maxvalue,v);
 78     }else
 79     {
 80     v = query(left,mid,lRoot,l,mid);
 81     maxvalue = std::max(maxvalue,v);
 82     v = query(mid+1,right,lRoot+1,mid+1,r);
 83     maxvalue = std::max(maxvalue,v);
 84     }
 85 
 86     return maxvalue;
 87 }
 88 
 89 int main()
 90 {
 91     int n,m;
 92 
 93     while(scanf("%d%d",&n,&m) != -1)
 94     {
 95     for(int i = 0;i < n;i ++)
 96     {
 97         scanf("%d",&scores[i+1]);
 98     }
 99             build(1,n,1);
100 
101     char str[3];
102 
103     for(int i = 0;i < m;i ++)
104     {
105         scanf("%s",str);
106         int a,b;
107         scanf("%d%d",&a,&b);
108         if(str[0] == 'Q')
109         {
110         printf("%d\n",query(1,n,1,a,b));
111         }else if(str[0] == 'U')
112         {
113         update(1,n,a,1,b);
114         }
115     }
116     }
117 
118     return 0;
119 }

 

posted on 2013-03-20 19:41  Shirlies  阅读(185)  评论(1编辑  收藏  举报