HDU1166-敌兵布阵

本文详细介绍了一种基本的数据结构——线段树,并通过一个具体的题目实例展示了如何使用线段树进行单点修改和区间查询操作。代码示例中包含了线段树的基本构造、更新及查询等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

http://acm.split.hdu.edu.cn/showproblem.php?pid=1166

思路

最基本的线段树,单点修改,区间查询

代码

#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;

#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
#define CLR(a, x) memset(a, x, sizeof(a))
#define FILL(a, n, x) for (int i = 0; i < n; i++) a[i] = x

const int maxn = 50000 << 2;
LL sumv[maxn];
int y1, y2, p, v;

void pushup(int o) {
    sumv[o] = sumv[lc] + sumv[rc];
}

void update(int o, int L, int R) {
    if (L == R) {
        sumv[o] += v;
        return;
    }
    int M = L + (R - L) / 2;
    if (p <= M) update(lc, L, M);
    else update(rc, M + 1, R);
    pushup(o);
}

LL query(int o, int L, int R) {
    if (y1 <= L && y2 >= R) return sumv[o];
    int M = L + (R - L) / 2;
    LL res = 0;
    if (y1 <= M) res += query(lc, L, M);
    if (y2 > M) res += query(rc, M + 1, R);
    return res;
}

void build(int o, int L, int R) {
    if (L == R) {
        scan(sumv[o]);
        return;
    }
    int M = L + (R - L) / 2;
    build(lc, L, M);
    build(rc, M + 1, R);
    pushup(o);
}

int main() {
    int T, n, kase = 0;
    char s[10];
    scan(T);
    while (T--) {
        scan(n);
        build(1, 1, n);
        printf("Case %d:\n", ++kase);
        while (scanf("%s", s) && s[0] != 'E') {
            if (s[0] == 'Q') {
                scan2(y1, y2);
                printf("%lld\n", query(1, 1, n));
            }
            if (s[0] == 'A') {
                scan2(p, v);
                update(1, 1, n);
            }
            if (s[0] == 'S') {
                scan2(p, v);
                v = -v;
                update(1, 1, n);
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值