hdu1166 敌兵布阵 线段树 单点更新

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

入门级单点更新线段树,sum维护区间总的人数

#include <set>
#include <map>
#include <queue>
#include <stack>
#include <deque>
#include <math.h>
#include <string>
#include <vector>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <functional>
#define mem(a) memset(a,0,sizeof(a));
#define mem_1(a) memset(a,-1,sizeof(a));
#define sf(a) scanf("%d",&a)
#define sff(a,b) scanf("%d%d",&a,&b)
#define sfff(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define LL long long
#define lson l, mid, root<<1
#define rson mid+1, r, root<<1|1
const int INF = 0x7FFFFFFF;
const int MAXN = 50000;
const double PI = acos(-1.0);
const double esp = 1e-10;
using namespace std;
struct node
{
    int l,r,sum;
}Tree[MAXN<<2];
void build_tree(int l, int r, int root)
{
    Tree[root].l = l;
    Tree[root].r = r;
    if(l == r)
    {
        scanf("%d",&Tree[root].sum);
       // cout << Tree[root].l << Tree[root].r << endl;
        return ;
    }
    int mid = (l + r) >> 1;

    build_tree(l,mid,root<<1);
    build_tree(mid+1,r,root<<1|1);
    Tree[root].sum = Tree[root << 1].sum + Tree[root << 1|1].sum;
}
void updata(int l,int r,int root,int k)
{
    if(l == Tree[root].l && r == Tree[root].r)
    {
        Tree[root].sum += k;
        return ;
    }
    int mid = (Tree[root].l + Tree[root].r) >> 1;
    if(r <= mid) updata(l,r,root<<1,k);
    else if(mid < l) updata(l,r,root<<1|1,k);
    else
    {
        updata(l,mid,root << 1,k);
        updata(mid+1,r,root << 1|1 , k);
    }
    Tree[root].sum = Tree[root << 1].sum + Tree[root << 1|1].sum;
}
int Query(int l,int r,int root)
{
    if(l == Tree[root].l && r == Tree[root].r)
        return Tree[root].sum;
    int mid = (Tree[root].l + Tree[root].r) >> 1;
    int ans = 0;
    if(r <= mid) ans += Query(l,r,root<<1);
    else if(mid < l) ans+=Query(l,r,root<<1|1);
    else
        ans+=Query(l,mid,root<<1) + Query(mid+1,r,root<<1|1);
    return ans;
}
int main()
{
    int T,l,r,n,times=1;
    char c[10];
    sf(T);
    while(T--)
    {
        sf(n);
        build_tree(1,n,1);
        printf("Case %d:\n", times++);
        while(cin >> c)
        {
            if(strcmp(c,"Query")==0)
            {
                sff(l,r);
                printf("%d\n",Query(l,r,1));
            }
            else if(strcmp(c,"Add")==0)
            {
                sff(l,r);
                updata(l,l,1,r);
            }
            else if(strcmp(c,"Sub")==0)
            {
                sff(l,r);
                updata(l,l,1,-r);
            }
            else
                break;
        }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值