您的位置:首页 > 其它

[HDOJ1754]I Hate It

2015-08-30 15:57 253 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1754

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

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <queue>
#include <map>
#include <stack>
#include <list>
#include <vector>

using namespace std;

const int maxn = 2000010;

typedef struct Node {
int value;
int left, right;
}Node;

Node node[maxn<<1];
int father[maxn];

inline int max(int a, int b) {
return a > b ? a : b;
}

void build(int left, int right, int i) {
node[i].left = left;
node[i].right = right;
node[i].value = 0;
if(left == right) {
father[left] = i;
return ;
}
build(((left+right)>>1)+1, right, (i<<1)+1);
build(left, (left+right)>>1, i<<1);
}

void update(int i) {
if(i == 1) {    //根节点
return ;
}
int fa = i / 2;
int a = node[2*fa].value;   //左儿子
int b = node[2*fa+1].value; //右儿子
node[fa].value = max(a, b); //
update(fa);
}

int ans;
void query(int left, int right, int i) {
if(node[i].left == left && node[i].right == right){
ans = max(ans, node[i].value);
return ;
}
//left
if(left <= node[2*i].right) {
if(right <= node[2*i].right) {
query(left, right, i<<1);
}
else {
query(left, node[2*i].right, i<<1);
}
}
//right
if(right >= node[2*i+1].left) {
if(left >= node[2*i+1].left) {
query(left, right, (i<<1)+1);
}
else {
query(node[2*i+1].left, right, (i<<1)+1);
}
}
}

int main() {
// freopen("in", "r", stdin);
int n, m;
char cmd[2];
int a, b, score;
while(~scanf("%d %d", &n, &m)) {
build(1, n, 1);
for(int i = 1; i <= n; i++) {
scanf("%d", &score);
node[father[i]].value = score;
update(father[i]);
}
while(m--) {
scanf("%s %d %d", cmd, &a, &b);
if(cmd[0] == 'Q') {
ans = 0;
query(a, b, 1);
printf("%d\n", ans);
}
else if(cmd[0] == 'U') {
node[father[a]].value = b;
update(father[a]);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: