啥都不会啊!怎么办啊!

Fitz

慢慢来生活总会好起来的!!!

A Simple Problem with Integers~POJ - 3468

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 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
 
这题也是线段树的模板题我上一篇写的是单点更新 这一篇为区间更新 。
这题很适合线段树入门。
 
 
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<queue>
 5 using namespace std;
 6 #define maxn 100005
 7 long long sum[maxn<<2],add[maxn<<2];
 8 void pushup(int rt) {
 9     sum[rt]=sum[rt<<1]+sum[rt<<1|1];
10 }
11 void pushdown(int rt ,int l) {
12     if (add[rt]) {
13         add[rt<<1]+=add[rt];
14         add[rt<<1|1]+=add[rt];
15         sum[rt<<1]+=add[rt]*(l-(l>>1));
16         sum[rt<<1|1]+=add[rt]*(l>>1);
17         add[rt]=0;
18     }
19 }
20 void build(int l,int r,int rt) {
21     if (l==r) {
22         scanf("%lld",&sum[rt]);
23         return ;
24     }
25     int m=(l+r)>>1;
26     build(l,m,rt<<1);
27     build(m+1,r,rt<<1|1);
28     pushup(rt);
29 }
30 void updata(int x,int y,int z,int l,int r,int rt) {
31     if (x<=l && r<=y) {
32         add[rt]+=z;
33         sum[rt]+=(long long)z*(r-l+1);
34         return ;
35     }
36     pushdown(rt,r-l+1);
37     int m=(l+r)>>1;
38     if (x<=m) updata(x,y,z,l,m,rt<<1);
39     if (y>m)  updata(x,y,z,m+1,r,rt<<1|1);
40     pushup(rt);
41 }
42 long long query(int x,int y,int l,int r,int rt) {
43     long long ans=0;
44     if (x<=l && r<=y ) return sum[rt];
45     pushdown(rt,r-l+1);
46     int m=(l+r)>>1;
47     if (x<=m) ans+=query(x,y,l,m,rt<<1);
48     if (y>m ) ans+=query(x,y,m+1,r,rt<<1|1);
49     return ans;
50 }
51 int main() {
52     int n,q;
53     while(scanf("%d%d",&n,&q)!=EOF) {
54         build(1,n,1);
55         char b[2];
56         int x,y,z;
57         while(q--) {
58             scanf("%s",b);
59             if (b[0]=='Q') {
60                 scanf("%d%d",&x,&y);
61                 printf("%lld\n",query(x,y,1,n,1));
62             } else {
63                 scanf("%d%d%d",&x,&y,&z);
64                 updata(x,y,z,1,n,1);
65             }
66         }
67     }
68     return 0;
69 }

 

posted @ 2018-03-04 19:07  Fitz~  阅读(192)  评论(0编辑  收藏  举报