hdu1166依旧是大山跑线段树题

也是不知不觉就会re 还不知道为什么 神经病题!害我做了这么长时间!!!

Sample Input
  
  
1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End


 

Sample Output
  
  
Case 1: 6 33 59
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 50001
int data[maxn];
int sum,n;
struct Tree
{
    int l,r;
    long long sum;
}tree[3*maxn];
void build(int l,int r,int pos)
{
    tree[pos].l=l;
    tree[pos].r=r;
    if(l==r)
    {
        tree[pos].sum=data[l];
        return;
    }
    int mid=(l+r)>>1;
    build(l,mid,2*pos);
    build(mid+1,r,2*pos+1);
    tree[pos].sum=tree[pos*2].sum+tree[pos*2+1].sum;
}
void Update(int pos,int a,int b)
{
    if(tree[pos].l==a&&tree[pos].r==a)
    {
        tree[pos].sum+=b;
        return;
    }
    int mid=(tree[pos].l+tree[pos].r)>>1;
    if(a<=mid)
        Update(pos*2,a,b);
    if(a>mid)
        Update(pos*2+1,a,b);
    tree[pos].sum+=b;
}
void Search(int pos,int a,int b)
{
    if(tree[pos].l==a&&tree[pos].r==b)
    {
        sum+=tree[pos].sum;
        return;
    }
    int mid=(tree[pos].l+tree[pos].r)>>1;
    if(b<=mid)
    {
        Search(pos*2,a,b);
    }
    else if(a>=mid+1)
    {
        Search(pos*2+1,a,b);
    }
    else
    {
        Search(pos*2,a,mid);
        Search(pos*2+1,mid+1,b);
    }
}
int main()
{
    int t,i,a,b,ans=0;
    string str;
    cin>>t;
    while(t--)
    {
        ans++;
        printf("Case %d:\n",ans);
        cin>>n;
        data[0]=0;
        for(i=1;i<=n;i++)
            scanf("%d",&data[i]);
        build(1,10,1);
        while(1){
        cin>>str;
        getchar();
        if(str=="End")   break;
        if(str=="Add")
        {
            scanf("%d%d",&a,&b);
            Update(1,a,b);
        }
        if(str=="Sub")
        {
            scanf("%d%d",&a,&b);
            Update(1,a,-b);
        }
        if(str=="Query")
        {
            scanf("%d%d",&a,&b);
            sum=0;
            Search(1,a,b);
            printf("%d\n",sum);
        }
        }
    }
    return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值