# 树状数组与线段树模板 JAVA

### Acwing1264 动态求连续区间和

1≤n≤1000001≤n≤100000,
1≤m≤1000001≤m≤100000，
1≤a≤b≤n1≤a≤b≤n

10 5
1 2 3 4 5 6 7 8 9 10
1 1 5
0 1 3
0 4 8
1 7 5
0 4 8


11
30
35


### 树状数组解法：

import java.io.BufferedReader;
import java.io.IOException;
public class Main{
static final int N = 100005;
static int []arr = new int [N + 5];
static int []tree = new int [N + 5];
static int n,m;
public static void main(String[] args) throws IOException {
n = Integer.parseInt(s1[0]);
m = Integer.parseInt(s1[1]);
for(int i = 1;i <= n;i ++) {
arr[i] = Integer.parseInt(s2[i-1]);
}
for(int i = 1;i <= n;i ++) {
}
for(int i = 0;i < m;i ++) {
int k = Integer.parseInt(s3[0]);
int a = Integer.parseInt(s3[1]);
int b = Integer.parseInt(s3[2]);
if(k == 0) {
System.out.println(query(b) - query(a-1));
}else {
}
}
}
static int lowbit(int x) {
return x & (-x);
}
static void add(int x,int v) {
for(int i = x;i <= n;i += lowbit(i)) {
tree[i] += v;
}
}
static int query(int x) {
int res = 0;
for(int i = x;i > 0;i -= lowbit(i)) {
res += tree[i];
}
return res;
}
}

### 线段树解法

import java.io.BufferedReader;
import java.io.IOException;
public class Main{
static final int N = 100005;
static int []arr = new int [N + 5];
static int []tree = new int [4*N + 5];
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(s1[0]);
int m = Integer.parseInt(s1[1]);
for(int i = 1;i <= n;i ++) {
arr[i] = Integer.parseInt(s2[i-1]);
}
build(1,1,n);
for(int i = 0;i < m;i ++) {
int k = Integer.parseInt(s3[0]);
int a = Integer.parseInt(s3[1]);
int b = Integer.parseInt(s3[2]);
if(k == 0) {
System.out.println(query(1,1,n,a,b));
}else {
update(1,1,n,a,b);
}
}
}
static void build(int node,int L,int R) {
if(L == R) {
tree[node] = arr[L];
return;
}
int mid = (L + R) >> 1;
int left_node  = node * 2 + 1;
int right_node = node * 2 + 2;
build(left_node,L,mid);
build(right_node,mid+1,R);
tree[node] = tree[left_node] + tree[right_node];
}
static void update(int node,int L,int R,int idx,int val) {
if(L == R) {
arr[idx] += val;
tree[node] = arr[idx];
return;
}
int mid = (L + R) >> 1;
int left_node  = node * 2 + 1;
int right_node = node * 2 + 2;
if(idx >= L && idx <= mid) {
update(left_node,L,mid,idx,val);
}
else {
update(right_node,mid+1,R,idx,val);
}
tree[node] = tree[left_node] + tree[right_node];
}
static int query(int node,int L,int R,int x,int y) {
if(x > R || y < L) {
return 0;
}
if(x <= L && y >= R) {
return tree[node];
}
int mid = (L + R) >> 1;
int left_node  = node * 2 + 1;
int right_node = node * 2 + 2;
int left_sum  = query(left_node,L,mid,x,y);
int right_sum = query(right_node,mid+1,R,x,y);
return left_sum + right_sum;
}
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客