码迷,mamicode.com
首页 > 其他好文 > 详细

[HDOJ1754]I Hate It

时间:2015-08-30 17:13:07      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1754

 

线段树单点更新,查询最值。代码如下:

 

  1 #include <cstdio>
  2 #include <cstdlib>
  3 #include <cstring>
  4 #include <algorithm>
  5 #include <iostream>
  6 #include <cmath>
  7 #include <queue>
  8 #include <map>
  9 #include <stack>
 10 #include <list>
 11 #include <vector>
 12 
 13 using namespace std;
 14 
 15 const int maxn = 2000010;
 16 
 17 typedef struct Node {
 18     int value;
 19     int left, right;
 20 }Node;
 21 
 22 Node node[maxn<<1];
 23 int father[maxn];
 24 
 25 inline int max(int a, int b) {
 26     return a > b ? a : b;
 27 }
 28 
 29 void build(int left, int right, int i) {
 30     node[i].left = left;
 31     node[i].right = right;
 32     node[i].value = 0;
 33     if(left == right) {
 34         father[left] = i;
 35         return ;
 36     }
 37     build(((left+right)>>1)+1, right, (i<<1)+1);
 38     build(left, (left+right)>>1, i<<1);
 39 }
 40 
 41 void update(int i) {
 42     if(i == 1) {    //根节点
 43         return ;
 44     }
 45     int fa = i / 2;
 46     int a = node[2*fa].value;   //左儿子
 47     int b = node[2*fa+1].value; //右儿子
 48     node[fa].value = max(a, b); //
 49     update(fa);
 50 }
 51 
 52 int ans;
 53 void query(int left, int right, int i) {
 54     if(node[i].left == left && node[i].right == right){
 55         ans = max(ans, node[i].value);
 56         return ;
 57     }
 58     //left
 59     if(left <= node[2*i].right) {
 60         if(right <= node[2*i].right) {
 61             query(left, right, i<<1);
 62         }
 63         else {
 64             query(left, node[2*i].right, i<<1);
 65         }
 66     }
 67     //right
 68     if(right >= node[2*i+1].left) {
 69         if(left >= node[2*i+1].left) {
 70             query(left, right, (i<<1)+1);
 71         }
 72         else {
 73             query(node[2*i+1].left, right, (i<<1)+1);
 74         }
 75     }
 76 }
 77 
 78 int main() {
 79     // freopen("in", "r", stdin);
 80     int n, m;
 81     char cmd[2];
 82     int a, b, score;
 83     while(~scanf("%d %d", &n, &m)) {    
 84         build(1, n, 1);
 85         for(int i = 1; i <= n; i++) {
 86             scanf("%d", &score);
 87             node[father[i]].value = score;
 88             update(father[i]);
 89         }
 90         while(m--) {
 91             scanf("%s %d %d", cmd, &a, &b);
 92             if(cmd[0] == Q) {
 93                 ans = 0;
 94                 query(a, b, 1);
 95                 printf("%d\n", ans);
 96             }
 97             else if(cmd[0] == U) {
 98                 node[father[a]].value = b;
 99                 update(father[a]);
100             }
101         }
102     }
103     return 0;
104 }

 

[HDOJ1754]I Hate It

标签:

原文地址:http://www.cnblogs.com/vincentX/p/4771044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!