poj3468 a simple problem with integers

来源:互联网 发布:r语言和c语言哪个难 编辑:程序博客网 时间:2024/06/05 07:42

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+1, ... , Ab.

Output

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

Sample Input
10 51 2 3 4 5 6 7 8 9 10Q 4 4Q 1 10Q 2 4C 3 6 3Q 2 4
Sample Output
455915
Hint
The sums may exceed the range of 32-bit integers.


直接用bit做会超时, 因为这里的加操作是对一个区间里的数都加

大白书上有线段树 和 bit的做法

直接对着敲的

感觉有的地方还不是那么理解 为什么会想到要这么做呢

树状数组ac代码:

#include<stdio.h>#include<string.h>#include<algorithm>#include<iostream>#include<limits>#include<stack>#include<stdio.h>#include<string.h>#include<algorithm>#include<iostream>#include<limits>#include<stack>using namespace std;const int DAT_SIZE = (1 << 18) - 1;const int MAX_N = 100005;const int MAX_Q = 100005;int N, Q;int A[MAX_N];char T[MAX_Q];int L[MAX_Q], R[MAX_Q], X[MAX_Q];long long data[DAT_SIZE], datb[DAT_SIZE];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);    }}long long 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{        long long 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;    }}void solve(){    for(int i = 0; i < N; i++){        add(i, i + 1, A[i], 0, 0, N);    }    for(int i = 0; i < Q; i++){        if(T[i] == 'C'){            add(L[i], R[i] + 1, X[i], 0, 0, N);        }        else{            printf("%lld\n",sum(L[i], R[i] + 1, 0, 0, N));        }    }}int main(){    while(scanf("%d%d",&N,&Q) != EOF){        for(int i = 0; i < N; i++){            scanf("%d",&A[i]);        }        for(int i = 0; i < Q; i++){            getchar();            scanf("%c",&T[i]);            if(T[i] == 'C'){                scanf("%d%d%d",&L[i],&R[i],&X[i]);            }            else{                scanf("%d%d",&L[i],&R[i]);            }        }        solve();    }    return 0;}


原创粉丝点击