codevs 1080 线段树练习

1080 线段树练习

 

时间限制: 1 s
空间限制: 128000 KB
题目等级 : 钻石 Diamond
 
 
 
题目描述 Description

一行N个方格,开始每个格子里都有一个整数。现在动态地提出一些问题和修改:提问的形式是求某一个特定的子区间[a,b]中所有元素的和;修改的规则是指定某一个格子x,加上或者减去一个特定的值A。现在要求你能对每个提问作出正确的回答。1N<100000,提问和修改的总数m<10000条。

输入描述 Input Description

输入文件第一行为个整数N,接下来是nn个整数,表示格子中原来的整数。接下一个正整数m,再接下来有m行,表示m个询问,第一个整数表示询问代号,询问代号1表示增加,后面的两个数xA表示给位置X上的数值增加A,询问代号2表示区间求和,后面两个整数表示ab,表示要求[a,b]之间的区间和。

输出描述 Output Description

共m行,每个整数

样例输入 Sample Input

6

3

4

1 3 5

2 1 4

1 1 9

2 2 6

样例输出 Sample Output

22

22

数据范围及提示 Data Size & Hint

1≤N≤100000, m≤10000 。

线段树

 1 //s d s
 2 #include<cstdio>
 3 #include<iostream>
 4 #include<cstdlib>
 5 using namespace std;
 6 const int N=300006;
 7 int a[N],sum[N];
 8 int b,c,d;
 9 
10 void update(int rt)
11 {
12     sum[rt]=sum[rt<<1]+sum[rt*2+1];
13 }
14 
15 void build(int l,int r,int rt)
16 {
17     if(l==r)
18     {
19         sum[rt]=a[l];
20         return ;
21     }
22     int m=(l+r)/2;
23     build(l,m,rt*2);
24     build(m+1,r,rt*2+1);
25     update(rt);    
26 }
27 
28 void modify(int l,int r,int rt,int p,int q)
29 {
30     if(r==l)
31     {
32         sum[rt]+=q;
33         return ;
34     }
35     int m=(r+l)/2;
36     if(p<=m)modify(l,m,rt*2,p,q);
37     else modify(m+1,r,rt*2+1,p,q);
38     update(rt);
39 }
40 
41 int ans=0;
42 int query(int l,int r,int rt,int nowl,int nowr)
43 {
44     if(nowl<=l&&nowr>=r)
45     {
46         return sum[rt];
47     }
48     int m=(r+l)/2;
49     int ans=0;
50     if(nowl<=m)ans+=query(l,m,rt*2,nowl,nowr);
51     if(nowr>m)ans+=query(m+1,r,rt*2+1,nowl,nowr);
52     return ans;
53     
54 }
55 int main()
56 {
57     int n;
58     scanf("%d",&n);
59     for(int i=1;i<=n;i++)scanf("%d",a+i);
60     build(1,n,1);
61     int m;
62     scanf("%d",&m);
63     
64     for(int i=1;i<=m;i++)
65     {
66         scanf("%d%d%d",&b,&c,&d);
67         if(b==1)
68         {
69             modify(1,n,1,c,d);
70         }
71         if(b==2)
72         {
73             printf("%d
",query(1,n,1,c,d));
74         }
75     }
76     return 0;
77         
78 }
原文地址:https://www.cnblogs.com/sssy/p/6822135.html