728x90
package javaSana.Day0917.segmentTree;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class B_1275 {
static int N, Q;
static long[] arr, tree;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
Q = Integer.parseInt(st.nextToken());
arr = new long[N + 1];
st = new StringTokenizer(br.readLine());
for (int i = 1; i <= N; i++) {
arr[i] = Long.parseLong(st.nextToken());
}
tree = new long[N * 4];
init(1, N, 1);
for (int i = 0; i < Q; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int a = Integer.parseInt(st.nextToken());
long b = Long.parseLong(st.nextToken());
int minN = Math.min(x, y);
int maxN = Math.max(x, y);
System.out.println(sum(1, N, 1, minN, maxN));
long dif = b - arr[a];
arr[a] = b;
update(1, N, 1, a, dif);
}
}
static long init(int start, int end, int node) {
if (start == end) {
return tree[node] = arr[start];
}
int mid = (start + end) / 2;
return tree[node] = init(start, mid, node * 2) + init(mid + 1, end, node * 2 + 1);
}
static void update(int start, int end, int node, int idx, long dif) {
if (idx < start || end < idx)
return;
tree[node] += dif;
if (start == end)
return;
int mid = (start + end) / 2;
update(start, mid, node * 2, idx, dif);
update(mid + 1, end, node * 2 + 1, idx, dif);
}
static long sum(int start, int end, int node, int left, int right) {
if (right < start || end < left) {
return 0;
}
if (left <= start && end <= right) {
return tree[node];
}
int mid = (start + end) / 2;
return sum(start, mid, node * 2, left, right) + sum(mid + 1, end, node * 2 + 1, left, right);
}
}
728x90
'Algorithm (Python, Java, SQL) > BaekJoon' 카테고리의 다른 글
[백준 14428] 수열과 쿼리 16 (0) | 2024.09.21 |
---|---|
[백준 2268번] 수들의 합 7 (0) | 2024.09.21 |
[백준 15724번] 주지수 (Java) (2) | 2024.01.30 |
[백준 3190번] 뱀 (Java) (0) | 2024.01.18 |
[백준 21921번] 블로그 (Python) (1) | 2023.11.13 |