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

线段树

时间:2019-02-07 23:46:09      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:floor   string   algorithm   cstring   dtree   pre   ++   turn   update   

求区间最大值

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxmnode = 1 << 18;
const int maxm = 5e4 + 5;


struct NODE {
int value;
int left, right;
} node[maxmnode];

int index[maxm];

void buildtree(int i, int left, int right) {
node[i].left = left;
node[i].right = right;
node[i].value = 0;
if(left == right) {
    index[left] = i;
    return;
}
buildtree(i << 1, left, (int)(floor(left + right) / 2.0));
buildtree((i << 1) + 1, (int)(floor(left + right) / 2.0) + 1, right);
}

void updatetree(int ri) {
if(ri == 1) return;
int fi = ri / 2;
int a = node[fi << 1].value;
int b = node[ (fi << 1) + 1 ].value;
node[fi].value = max(a, b);
updatetree(fi);
}

int MAX;

void query(int i, int l, int  r) {
if(node[i].left == l && node[i].right == r) {
    MAX = max(MAX, node[i].value);
    return;
}
i = i << 1;
if(l <= node[i].right) {
    if(r <= node[i].right) query(i, l, r);
    else query(i, l ,node[i].right);
}
i++;
if(r >= node[i].left) {
    if(l >= node[i].left) query(i, l, r);
    else query(i, node[i].left, r);
}

}



int main() {
int n, m, q;
while(~scanf("%d%d", &n, &m)) {
    buildtree(1, 1, n);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &q);
        node[ index[i] ].value = q;
        updatetree(index[i]);
    }
    char ch[10];
    int a,b;
    while(m--) {
        scanf("%s%d%d", ch, &a, &b);
        if(ch[0] == Q) {
            MAX = 0;
            query(1, a, b);
            printf("%d\n", MAX);
        }
        else {
            node[ index[a] ].value = b;//值无所谓,b;
            updatetree(index[a]);
        }
    }
}


return 0;
}

 

线段树

标签:floor   string   algorithm   cstring   dtree   pre   ++   turn   update   

原文地址:https://www.cnblogs.com/downrainsun/p/10355710.html

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