POJ 3468 A Simple Problem with Integers(線段樹|區間加減&&區間求和)

來源:互聯網
上載者:User

題目連結:點擊開啟連結

題意:區間加減,區間求和。

該題是線段樹區間增減和區間求和的模板題。 和區間修改值一樣, 在每個結點上維護一個之前加減的值, 那麼每次經過一個結點時, 當前結點一定已經擁有所有結點資訊。

每次遞迴前下傳結點資訊,這就是所謂的懶惰標記。 

細節參見代碼:

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<string>#include<vector>#include<stack>#include<bitset>#include<cstdlib>#include<cmath>#include<set>#include<list>#include<deque>#include<map>#include<queue>#define Max(a,b) ((a)>(b)?(a):(b))#define Min(a,b) ((a)<(b)?(a):(b))using namespace std;typedef long long ll;const double PI = acos(-1.0);const double eps = 1e-6;const int INF = 1000000000;const int maxn = 100000 + 10;int T,n,l,r,q,v;ll sum[maxn<<2],addv[maxn<<2];char s[10];void push_up(int o) {    sum[o] = sum[o<<1] + sum[o<<1|1];}void build(int l, int r, int o) {    int m = (l + r) >> 1;    addv[o] = 0;    if(l == r) {        scanf("%lld",&sum[o]);        return ;    }    build(l, m, o<<1);    build(m+1, r, o<<1|1);    push_up(o);}void pushdown(int o, int l, int r) {    if(addv[o]) {        int m = (l + r) >> 1;        addv[o<<1] += addv[o];        addv[o<<1|1] += addv[o];        sum[o<<1] += (ll)(m - l + 1) * addv[o];        sum[o<<1|1] += (ll)(r - m) * addv[o];        addv[o] = 0;    }}void update(int L, int R, int v, int l, int r, int o) {    int m = (l + r) >> 1;    if(L <= l && r <= R) {        addv[o] += v;        sum[o] += (ll)v * (r - l + 1);        return ;    }    pushdown(o, l, r);    if(L <= m) update(L, R, v, l, m, o<<1);    if(m < R) update(L, R, v, m+1, r, o<<1|1);    push_up(o);}ll query(int L, int R, int l, int r, int o) {    int m = (l + r) >> 1;    if(L <= l && r <= R) {        return sum[o]; //當前結點一定已經擁有所有的標記    }    ll ans = 0;    pushdown(o, l, r);    if(L <= m) ans += query(L, R, l, m, o<<1);    if(m < R) ans += query(L, R, m+1, r, o<<1|1);    push_up(o);    return ans;}int main() {    while(~scanf("%d%d",&n,&q)) {        build(1, n, 1);        while(q--) {            scanf("%s%d%d",s,&l,&r);            if(s[0] == 'Q') {                printf("%lld\n",query(l, r, 1, n, 1));            }            else {                scanf("%d",&v);                update(l, r, v, 1, n, 1);            }        }    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.