HDU 4027 Can you answer these queries?(线段树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4027


这个题目想明白就是裸线段树,sqrt,每个节点最多更新次数有限,一旦变为1之后就不用更新了,利用这个特点就OK了!


#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <cmath>
using namespace std;
#define maxn 120100
#define LL long long
int n,m;
struct point{
    int l,r;
    LL sum;
}po[maxn*3];
LL value,score[maxn];
int build_tree(int root,int l,int r){
    po[root].l=l,po[root].r=r;
    if(l==r) {scanf("%I64d",&po[root].sum);return 0;}
    int mid=(l+r)>>1;
    build_tree(root<<1,l,mid),build_tree((root<<1)|1,mid+1,r);
    po[root].sum=po[root<<1].sum+po[(root<<1)|1].sum;
    return 0;
}
int update(int root,int l,int r){
    if(po[root].l==l && po[root].r==r && po[root].sum==po[root].r-po[root].l+1) return 0;
    if(po[root].l == po[root].r){
        po[root].sum=(LL)sqrt(po[root].sum*1.0);return 0;
    }
    int mid=(po[root].l+po[root].r)>>1;
    if(r<=mid) update(root<<1,l,r);
    else if(l>mid) update((root<<1)|1,l,r);
    else update(root<<1,l,mid),update((root<<1)|1,mid+1,r);
    po[root].sum=po[root<<1].sum+po[(root<<1)|1].sum;
    return 0;
}
LL query(int root,int l,int r){
    if(po[root].l==l && po[root].r==r)
    return po[root].sum;
    int mid=(po[root].l+po[root].r)>>1;
    if(r<=mid) return query(root<<1,l,r);
    else if(l > mid) return query((root<<1)|1,l,r);
    else return query(root<<1,l,mid)+query((root<<1)|1,mid+1,r);
}
int main(){
    int i,j,k=0,t,a,b;
    while(scanf("%d",&n)!=EOF){
        build_tree(1,1,n);
        printf("Case #%d:\n",++k);
        scanf("%d",&m);
        for(i=0;i<m;i++){
            scanf("%d%d%d",&t,&a,&b);
            if(a>b) swap(a,b);
            if(t==0) update(1,a,b);
            else printf("%I64d\n",query(1,a,b));
        }
        printf("\n");
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值