HDU 1166 线段树

方法一:>o<
线段树
模板题
代码如下

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
const int maxn=500000+10;
struct tree{
    int lef,rig,mid,sum;
}t[maxn];
int cas,len,cnt,a;
void init(int a,int b,int n){
    t[n].lef=a,t[n].rig=b;
    t[n].mid=(a+b)/2,t[n].sum=0;
    if(a+1==b)
        return;
    init(a,(a+b)/2,2*n);//左子树---------左闭右开 
    init((a+b)/2,b,2*n+1);//右子树 
}
void creat(int pos,int val,int n){
    t[n].sum+=val;
    if(t[n].lef+1==t[n].rig)
        return;
    if(pos<t[n].mid)
        creat(pos,val,2*n);//左子树 
    else
        creat(pos,val,2*n+1);
}
int query(int x,int y,int n){
    if(t[n].lef==x&&t[n].rig==y)
        return t[n].sum;
    if(x<t[n].mid){
        if(y<=t[n].mid)
            return query(x,y,n*2);
        else
            return query(x,t[n].mid,2*n)+query(t[n].mid,y,2*n+1);
    }
    else
        return query(x,y,2*n+1);
}
int main(){
    scanf("%d",&cas),cnt=1;
    while(cas--){
        char ord[10];
        scanf("%d",&len),init(1,len+1,1);
        for(int i=1;i<=len;i++)
            scanf("%d",&a),creat(i,a,1);
        int x,y;
        printf("Case %d:\n",cnt++);
        while(scanf("%s",ord)){
            if(!strcmp(ord,"End"))
                break;
            scanf("%d%d",&x,&y);
            if(strcmp(ord,"Query")==0)
                printf("%d\n",query(x,y+1,1));
            else if(strcmp(ord,"Add")==0)
                creat(x,y,1);
            else if(strcmp(ord,"Sub")==0)
                creat(x,-y,1);
        }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值