HDU1166敌兵布阵-线段树求和

HDU1166敌兵布阵-线段树求和


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
const int maxn = 200005*2;
long long n,dat[2*maxn-1];
void init(int n_)
{
    n = 1;
    while(n<n_)n*=2;
    for(int i = 0 ;i < 2*n-1;i++)
        dat[i]= 0;
}
void update(int k,int a)
{
    k += n-1;
    dat[k] += a;
    while(k>0)
    {
        k = (k-1)/2;
        dat[k]+=a;
    }
}
int query(int a, int b,int k,int l ,int r)
//查询用 query(a,b,0,0,n)·查询[a,b)
{
    if(r<=a||b<=l){return 0;}
    if(a<=l&&r<=b)return dat[k];
    else
    {
        int vl = query(a,b,k*2+1,l,(l+r)/2);
        int vr = query(a,b,k*2+2,(l+r)/2,r);
        return vl+vr;
    }
}
int main()
{
    int m,a;
    char op[10];
    cin>>m;
    for(int k = 1; k <= m ; k++)
    {
        cout<<"Case "<<k<<":"<<endl;
        scanf("%d",&n);
        init(n);
        for(int i = 0 ; i < n; i++)
        {
            scanf("%d",&a);
            update(i,a);
        }
        int op1,op2;
        scanf("%s",op);
        while(strcmp(op,"End"))
        {
            scanf("%d %d",&op1,&op2);
            if(strcmp(op,"Query")==0)
            {
                printf("%d\n",query(op1-1,op2,0,0,n));
            }
            else if(strcmp(op,"Add")==0)
            {
                update(op1-1,op2);
            }
            else if(strcmp(op,"Sub")==0)
            {
                update(op1-1,-op2);
            }
            getchar();
            scanf("%s",op);
        }
    }
    return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值