前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >POJ 3468 A Simple Problem with Integers(线段树区间更新)

POJ 3468 A Simple Problem with Integers(线段树区间更新)

作者头像
Ch_Zaqdt
发布2019-01-11 11:38:20
4040
发布2019-01-11 11:38:20
举报
文章被收录于专栏:Zaqdt_ACM

题目连接:http://poj.org/problem?id=3468

       题意就是给了n个数,有m次操作,当输入Q的时候问a到b的总和是多少,当输入为C的时候表示从a到b都加上c。

       简单的区间更新操作,只是需要注意题目要求的是加上c而不是更改为c,所以在更新的时候需要+=而不是=,还有就是记得开long long。

AC代码:

代码语言:javascript
复制
#include <iostream>
#include <cstdio>
#include <cstring>
#define lson l, mid, o << 1
#define rson mid + 1, r, o << 1 | 1
#define maxn 100005
#define ll long long
using namespace std;
int n,m;
ll pre[maxn << 2],add[maxn << 2];
string str;

void Pushup(ll o){
  pre[o] = pre[o << 1] + pre[o << 1 | 1];
}

void Pushdown(ll o,ll ans){
  if(add[o]){
    add[o << 1] += add[o];         // 注意是+=
    add[o << 1 | 1] += add[o];
    pre[o << 1] += add[o] * (ans - (ans >> 1));
    pre[o << 1 | 1] += add[o] * (ans >> 1);
    add[o] = 0;
  }
}

void Build(ll l,ll r,ll o){
  add[o] = 0;
  if(l == r){
    scanf("%lld",&pre[o]);
    return ;
  }
  ll mid = (l + r) >> 1;
  Build(lson);
  Build(rson);
  Pushup(o);
}

void Update(ll L,ll R,ll ans,ll l,ll r,ll o){
  if(L <= l && r <= R){
    pre[o] += ans * (r - l + 1);
    add[o] += ans;
    return ;
  }
  Pushdown(o, r - l + 1);
  ll mid = (l + r) >> 1;
  if(L <= mid)Update(L,R,ans,lson);
  if(R > mid)Update(L,R,ans,rson);
  Pushup(o);
}

ll Query(ll L,ll R,ll l,ll r,ll o){
  if(L <= l && r <= R){
    return pre[o];
  }
  ll mid = (l + r) >> 1;
  Pushdown(o,r - l + 1);
  ll ans = 0;
  if(L <= mid) ans += Query(L,R,lson);
  if(R > mid) ans += Query(L,R,rson);
  return ans;
}

int main()
{
  scanf("%d%d",&n,&m);
  Build(1,n,1);
  while(m--){
    cin>>str;
    if(str == "Q"){
      ll a,b;
      scanf("%lld%lld",&a,&b);
      printf("%lld\n",Query(a,b,1,n,1));
    }
    else{
      ll a,b,c;
      scanf("%lld%lld%lld",&a,&b,&c);
      Update(a,b,c,1,n,1);
    }
  }
  return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年07月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档