POJ3468 A Simple Problem with Integers (Line Segment Tree)

A Simple Problem with Integers

Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 129246 Accepted: 40098
Case Time Limit: 2000MS

Description

You have N integers, A*1, *A*2, … , *AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.

Input

The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A*1, *A*2, … , *AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
“C a b c” means adding c to each of Aa, Aa+1, … , Ab. -10000 ≤ c ≤ 10000.
“Q a b” means querying the sum of Aa, Aa +1, … , Ab .

Output

You need to answer all Q commands in order. One answer in a line.

Sample Input

10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4

Sample Output

4
55
9
15

meaning of the title

  n number of m operations, Q is the query, C is the change interval.

Problem solving ideas

  The line segment tree solves it, pay attention to the explosion of int.

code

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e5+50;

long long arr[maxn<<2],Add[maxn<<2];//不用longlong会炸
void pushup(int rt)
{
    arr[rt]=arr[rt<<1]+arr[rt<<1|1];
}
void build(int l,int r,int rt)
{
    Add[rt]=0;//记得清0
    if(l==r)
    {
        cin>>arr[rt];
        return;
    }
    int m=(l+r)>>1;
    build(l,m,rt<<1);
    build(m+1,r,rt<<1|1);
    pushup(rt);
}
void pushdown(int rt,int ln,int rn)
{
    if(Add[rt])
    {
        Add[rt<<1]+=Add[rt];
        Add[rt<<1|1]+=Add[rt];
        arr[rt<<1]+=Add[rt]*ln;
        arr[rt<<1|1]+=Add[rt]*rn;
        Add[rt]=0;
    }
}
void update(int L,int R,int c,int l,int r,int rt)
{
    if(L<=l&&R>=r)
    {
        arr[rt]+=c*(r-l+1);
        Add[rt]+=c;
        return;
    }
    int m=(l+r)>>1;
    pushdown(rt,m-l+1,r-m);
    if(L<=m) update(L,R,c,l,m,rt<<1);
    if(R> m) update(L,R,c,m+1,r,rt<<1|1);
    pushup(rt);
}
long long query(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r) return arr[rt];
    int m=(l+r)>>1;
    pushdown(rt,m-l+1,r-m);
    long long ans=0;
    if(L<=m) ans+=query(L,R,l,m,rt<<1);
    if(R> m) ans+=query(L,R,m+1,r,rt<<1|1);
    return ans;
}
int main()
{
//    freopen("in.txt","r",stdin);
    ios::sync_with_stdio(false);
    int n,m;
    cin>>n>>m;
    build(1,n,1);
    string str;
    int a,b,c;
    while(m--)
    {
        cin>>str;
        if(str=="Q")
        {
            cin>>a>>b;
            printf("%lld\n",query(a,b,1,n,1));
        }
        else
        {
            cin>>a>>b>>c;
            update(a,b,c,1,n,1);
        }
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325961248&siteId=291194637