Home BOJ. Array and Query (16975)
Post
Cancel

BOJ. Array and Query (16975)

[Link] https://www.acmicpc.net/problem/16975

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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static long[] seg;
	static int[] orig;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String[] line;
		int n = toi(br.readLine());
		orig = getLine();
		seg = new long[1 << (int)Math.ceil(Math.log(n) / Math.log(2)) + 1];
		initSegTree(0, n - 1, 1);

		int qnum = toi(br.readLine());
		for(int i = 0 ; i < qnum; i++) {
			orig = getLine();
			if(orig[0] == 1) {
				update(0, n - 1, 1, orig[1] - 1, orig[2] - 1, orig[3]);
			} else {
				sb.append(get(0, n - 1, 1, orig[1] - 1)).append("\n");
			}
		}

		print(sb);
	}

	static void update(int left, int right, int idx, int from, int to, int add) {
		if(right < from || to < left) return;
		if(from <= left && right <= to) {
			seg[idx] += add;
			return;
		}
		int mid = (left + right) / 2;
		update(left, mid, 2*idx, from , to, add);
		update(mid + 1, right, 2*idx+1, from, to, add);
	}

	static long get(int left, int right, int idx, int target) {
		if(target < left || right < target) return 0l;
		if(left == right) return seg[idx];
		int mid = (left + right) / 2;
		return seg[idx] + get(left, mid, 2*idx, target) + get(mid + 1, right, 2*idx + 1, target);
	}

	static void initSegTree(int from, int to, int idx) {
		if(from == to) {
			seg[idx] = (long)orig[from];
			return;
		}
		int mid = (from + to) / 2;
		initSegTree(from, mid, 2*idx);
		initSegTree(mid + 1, to, 2*idx + 1);
	}

	static int toi(String s) { return Integer.parseInt(s); }
	// static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getLine() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.