-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
65 lines (58 loc) · 1.26 KB
/
Copy pathMain.java
File metadata and controls
65 lines (58 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner io = new Scanner(System.in);
int n = io.nextInt();
int q = io.nextInt();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = io.nextInt();
}
SegmentTree seg = new SegmentTree(n + 1);
for (int i = 1; i <= n; i++) {
seg.add(i, arr[i] - arr[i - 1]);
}
for (int i = 0; i < q; i++) {
int operation = io.nextInt();
if (operation == 1) {
int a = io.nextInt();
int b = io.nextInt();
int u = io.nextInt();
seg.add(a, u);
if (b < n) seg.add(b + 1, -u);
} else {
int k = io.nextInt();
System.out.println(seg.sum(0, k));
}
}
io.close();
}
static class SegmentTree {
private long[] tree;
private int n;
public SegmentTree(int n) {
this.n = n;
tree = new long[n * 2];
}
public long sum(int a, int b) {
a += n;
b += n;
long sum = 0;
while (a <= b) {
if (a % 2 == 1) sum += tree[a++];
if (b % 2 == 0) sum += tree[b--];
a /= 2;
b /= 2;
}
return sum;
}
public void add(int index, long amount) {
index += n;
tree[index] += amount;
for (index /= 2; index >= 1; index /= 2) {
tree[index] = tree[2 * index] + tree[2 * index + 1];
}
}
}
}