HDU 1166 敌兵布阵(基础线段树~)

来源:互联网 发布:金蝶软件财务报表 编辑:程序博客网 时间:2024/05/15 11:54

简单滴线段树,直接上码吧

#include <cstdio>#include <cstring>#include <iostream>using namespace std;int tree[50005 << 2]; //tree存放的是子树的和#define lson l, m, rt << 1#define rson m + 1, r, (rt << 1) | 1void pushup(int rt){    tree[rt] = tree[rt << 1] + tree[(rt << 1) | 1];}int Query(int L, int R, int l, int r, int rt) //子区间L-R的和{    if (L <= l && r <= R)    {        return tree[rt];    }    else    {        int ans = 0;        int m = (l + r) >> 1;        if (L <= m)            ans += Query(L, R, lson);        if (m < R)            ans += Query(L, R, rson);        return ans;    }}void update(int pos, int val, int l, int r, int rt){    if (l == r)    {        tree[rt] += val;    }    else    {        int m = (l + r) >> 1;        if (pos <= m)            update(pos, val, lson);        else            update(pos, val, rson);        pushup(rt);    }}void build(int l, int r, int rt){    if (l == r)    {        scanf("%d", &tree[rt]);        return;    }    else    {        int m = (l + r) >> 1;        build(lson);        build(rson);        pushup(rt);    }}int main(){    int t;    int kase = 0;    scanf("%d", &t);    while (t--)    {        printf("Case %d:\n", ++kase);        memset(tree, 0, sizeof(tree));        int n;        scanf("%d", &n);        build(1, n, 1);        char s[30];        int a, b;        while (~scanf("%s", s)) //对应操作.        {            if (s[0] == 'E')                break;            scanf("%d%d", &a, &b);            if (s[0] == 'Q')                printf("%d\n", Query(a, b, 1, n, 1));            else if (s[0] == 'S')                update(a, -b, 1, n, 1);            else                update(a, b, 1, n, 1);        }    }}


原创粉丝点击