POJ 3468 A Simple Problem with Integers ——————线段树,维护区间

版权声明:听说这里是写版权声明的 https://blog.csdn.net/Hpuer_Random/article/details/81941251

A Simple Problem with Integers

Language:Default
A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 141040 Accepted: 43753
Case Time Limit: 2000MS

Description

You have N integers, A1, A2, … , 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 A1, A2, … , 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

Hint

The sums may exceed the range of 32-bit integers.

Source

——- 线段树,区间查询及更改区间的值(给一个区间所有的数都加上一个值)
/*
 *  白书的板子
 *  认真思考,仔细理解
 */

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
typedef long long ll;
const int MAX_N=1e5+7;
const int DAT_SIZE=1<<20;
int N,Q;
int A[MAX_N];
char T[MAX_N];
int L[MAX_N],R[MAX_N],X[MAX_N];
// 线段树
ll data[DAT_SIZE],datb[DAT_SIZE];

/*
 *  对区间[a, b)同时加x
 *  k 是节点的编号,对应的是区间[l, r)
 */

void add(int a, int b, int x, int k,int l,int r)
{
    if(a <= l && r <= b)    data[k] += x;
    else if(l < b && a < r)
    {
        datb[k] += (min(b,r) - max(a,l))*x;
        add(a, b, x, k * 2 + 1, l, (l + r) / 2);
        add(a, b, x, k * 2 + 2, (l + r) / 2, r);
    }
}

/*
 *  计算[a, b)的和
 *  k 是节点的编号,对应的是区间[l, r)
 */

ll sum(int a, int b, int k, int l, int r)
{
    if(b <= l || r <= a)        return 0;
    else if(a <= l && r <= b)   return data[k] * (r - l) + datb[k];
    else
    {
        ll res = (min(b, r) - max(a, l)) * data[k];
        res += sum(a, b, k * 2 + 1, l, (l + r) / 2);
        res += sum(a, b, k * 2 + 2, (l + r) / 2, r);
        return res;
    }
}
int main()
{
    ios::sync_with_stdio(0);
    cin>>N>>Q;
    for(int i=0;i<N;i++)
    {
        cin>>A[i];
        add(i,i+1,A[i],0,0,N);
    }
    for(int i=0;i<Q;i++)
    {
        cin>>T[i];
        if(T[i]=='C')
        {
            cin>>L[i]>>R[i]>>X[i];
            add(L[i]-1, R[i], X[i], 0, 0, N);
//            cout<<T[i]<<L[i]<<R[i]<<X[i]<<endl;
        }
        else
        {
            cin>>L[i]>>R[i];
            cout<<sum(L[i]-1, R[i], 0, 0, N)<<endl;
//            cout<<T[i]<<L[i]<<R[i]<<endl;
        }
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/Hpuer_Random/article/details/81941251