Can you answer these queries? HDU - 4027 区间修改&&(优化)

Can you answer these queries? HDU - 4027

题意

给定n个数,分别代表每一个战舰的耐力值。有m个操作,当 t=1时,输出x~y的战舰耐力值之和,当 t=0时,使x~y战舰的每一个耐力值都变为原来的平方根(向下取整)。

思路

遍历 x到y 的每一个叶子节点,使他们的值变为原来的平方根,结果超时了。因为 1 的平方根还是 1,所以在更新时判断这段区间的值是否都为1,如果都为1就不需要更新。

一开始以为会用到标记数组,最后发现根本不许需要那么麻烦。。。

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=262144;
ll sum[maxn],node[maxn/2];
void pushup(int rt)
{
    sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void bulid(int l,int r,int rt)
{
    if(l==r)
    {
        sum[rt]=node[l];
        return ;
    }
    int m=(l+r)>>1;
    bulid(l,m,rt<<1);
    bulid(m+1,r,rt<<1|1);
    pushup(rt);
}
void update(int L,int R,int l,int r,int rt)  //更新 L~R区间
{
    if(l==r)
    {
        sum[rt]=sqrt(sum[rt]);
        return ;
    }
    if(L<=l && R>=r && sum[rt]==r-l+1)  //优化  判断区间的值是否都为1
        return ;
    int m=(l+r)>>1;
    if(L<=m)
        update(L,R,l,m,rt<<1);
    if(R>m)
        update(L,R,m+1,r,rt<<1|1);
    pushup(rt);
}
ll query(int L,int R,int l,int r,int rt)  // L~R区间求和
{
    if(L<=l && R>=r)
        return sum[rt];
    ll cnt=0;
    int m=(l+r)>>1;
    if(L<=m)
        cnt+=query(L,R,l,m,rt<<1);
    if(R>m)
        cnt+=query(L,R,m+1,r,rt<<1|1);
    return cnt;
}
int main()
{
    int n,m,k=1;
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;i++)
            scanf("%lld",&node[i]);
        bulid(1,n,1);
        scanf("%d",&m);
        int x,y,z;
        printf("Case #%d:\n",k++);
        while(m--)
        {
            scanf("%d%d%d",&z,&x,&y);
            if(x>y)      //当 x>y时,交换两点的值
                swap(x,y);
            if(z==1)
                printf("%lld\n",query(x,y,1,n,1));
            else
                update(x,y,1,n,1);
        }
        printf("\n");
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值