Noob Dream

 找回密码
 加入我们[Register]
搜索
查看: 82|回复: 0

线段树(单点更新)

[复制链接]

4

主题

4

帖子

73

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
73
发表于 2018-5-6 21:05:33 | 显示全部楼层 |阅读模式
教学视频:https://www.bilibili.com/video/av22947926

算法模板
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

#define lson x << 1
#define rson (x << 1) + 1

const int maxn = 200000 + 5;
int tree[maxn << 2];
int arr[maxn];
int ans;
int n, m;

void Create(int x, int l, int r) {
    if (l == r) {
        tree[x] = arr[l];
        return;
    }
    int mid = (l + r) / 2;
    Create(lson, l, mid);
    Create(rson, mid + 1, r);
    tree[x] = max(tree[lson], tree[rson]);
}

void Update(int x, int l, int r, int pos, int val) {
    if (l >= r) {
        tree[x] = val;
        return;
    }
    int mid = (l + r) / 2;
    if (pos <= mid) Update(lson, l, mid, pos, val);
    if (pos > mid) Update(rson, mid + 1, r, pos, val);
    tree[x] = max(tree[lson], tree[rson]);
}

void Query(int x, int l, int r, int L, int R) {
    if (L <= l && R >= r) {
        ans = max(ans, tree[x]);
        return;
    }
    int mid = (l + r) / 2;
    if (L <= mid) Query(lson, l, mid, L, R);
    if (R > mid) Query(rson, mid + 1, r, L, R);
}


int main() {
    while (scanf("%d%d", &n, &m) != EOF) {
        for (int i = 1; i <= n; i++) scanf("%d", &arr[i]);
        Create(1, 1, n);
        while (m--) {
            ans = 0;
            char ch;
            int a, b;
            scanf("%s", &ch);
            scanf("%d%d", &a, &b);
            if (ch == 'U') {
                Update(1, 1, n, a, b);
            }
            else {
                Query(1, 1, n, a, b);
                printf("%d\n", ans);
            }
        }
    }
    return 0;
}


回复

使用道具 举报

本版积分规则

QQ|Noob Dream

GMT+8, 2018-8-15 12:54 , Processed in 0.156342 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表