poj 3468 A Simple Problem with Integers 线段树

题目链接:http://poj.org/problem?id=3468

以前看过线段树,不过没看明白,也没做过这类题;这次一定要搞懂!!!再次看了两天的线段树,开始有点明白了,多谢媛神博客的支持。

View Code
  1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4 using namespace std;
5 #define L(x) (x<<1)
6 #define R(x) (x<<1|1)
7 #define MID(x,y) ((x+y)>>1)
8 const int MAX=100005;
9 struct Tnode{
10 __int64 sum,a;
11 int left,right;
12 }node[MAX*4];
13 int num[MAX];
14 void INit()
15 {
16 memset(node,0,sizeof(node));
17 }
18 void Bulid(int t,int l,int r)
19 {
20 node[t].left=l;
21 node[t].right=r;
22 if(l+1==r)
23 {
24 node[t].sum=num[l];
25 return ;
26 }
27 int mid=MID(l,r);
28 Bulid(L(t),l,mid);
29 Bulid(R(t),mid,r);
30 node[t].sum=node[L(t)].sum+node[R(t)].sum;
31 }
32 void update(int t,int l,int r,__int64 sum)
33 {
34 if(node[t].left==l&&node[t].right==r)
35 {
36 node[t].a+=sum;
37 node[t].sum+=(node[t].right-node[t].left)*sum;
38 return ;
39 }
40 if(node[t].a)
41 {
42 node[L(t)].a+=node[t].a;
43 node[R(t)].a+=node[t].a;
44 node[L(t)].sum+=node[t].a*(node[L(t)].right-node[L(t)].left);
45 node[R(t)].sum+=node[t].a*(node[R(t)].right-node[R(t)].left);
46 node[t].a=0;
47 }
48 int mid=MID(node[t].left,node[t].right);
49 if(l>=mid) update(R(t),l,r,sum);
50 else if(r<=mid) update(L(t),l,r,sum);
51 else {
52 update(L(t),l,mid,sum);
53 update(R(t),mid,r,sum);
54 }
55 node[t].sum=node[L(t)].sum+node[R(t)].sum;
56 }
57
58 __int64 Query(int t,int l,int r)
59 {
60 if(node[t].left==l&&node[t].right==r)
61 {
62 return node[t].sum;
63 }
64 if(node[t].a)
65 {
66 node[L(t)].a+=node[t].a;
67 node[R(t)].a+=node[t].a;
68 node[L(t)].sum+=node[t].a*(node[L(t)].right-node[L(t)].left);
69 node[R(t)].sum+=node[t].a*(node[R(t)].right-node[R(t)].left);
70 node[t].a=0;
71 }
72 int mid=MID(node[t].left,node[t].right);
73 if(l>=mid) return Query(R(t),l,r);
74 else if(r<=mid) return Query(L(t),l,r);
75 else
76 return (Query(L(t),l,mid)+Query(R(t),mid,r));
77 }
78 int main()
79 {
80 char s[10];
81 int n,m,i,x,y;
82 __int64 z;
83 while(scanf("%d%d",&n,&m)!=EOF)
84 {
85 INit();
86 for(i=0;i<n;i++)
87 scanf("%d",&num[i]);
88 Bulid(1,0,n+1);
89 while(m--)
90 {
91 scanf("%s",s);
92 if(s[0]=='Q'){
93 scanf("%d%d",&x,&y);
94 printf("%I64d\n",Query(1,x-1,y));
95 }
96 else{
97 scanf("%d%d%I64d",&x,&y,&z);
98 if(z==0)continue;
99 update(1,x-1,y,z);
100 }
101 }
102 }
103 return 0;
104 }

 

 

posted @ 2012-02-27 12:30  我们一直在努力  阅读(194)  评论(0编辑  收藏  举报