Skip to content

Commit ba9ea19

Browse files
authored
[20250319] BOJ / 골드1 / 구간합 구하기 / 이강현
1 parent 4b69de7 commit ba9ea19

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class Main {
6+
static int N;
7+
static int M;
8+
static int K;
9+
static long[] arr;
10+
static long[] tree;
11+
public static void main(String[] args) throws Exception {
12+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
14+
StringTokenizer st = new StringTokenizer(br.readLine());
15+
N = Integer.parseInt(st.nextToken());
16+
M = Integer.parseInt(st.nextToken());
17+
K = Integer.parseInt(st.nextToken());
18+
arr = new long[N*4];
19+
tree = new long[N*4];
20+
21+
for(int i=1;i<=N;i++){
22+
arr[i] = Long.parseLong(br.readLine());
23+
}
24+
init(1,1,N);
25+
for(int i=0;i<M+K;i++){
26+
st = new StringTokenizer(br.readLine());
27+
int option = Integer.parseInt(st.nextToken());
28+
int arg1 = Integer.parseInt(st.nextToken());
29+
long arg2 = Long.parseLong(st.nextToken());
30+
if(option == 1){//수정
31+
update(1,1,N,arg1,arg2-arr[arg1]);
32+
arr[arg1] = arg2;
33+
}else if(option == 2){//구간 합
34+
bw.write(query(1,1,N,arg1,(int)arg2) + "\n");
35+
}
36+
}
37+
bw.close();
38+
}
39+
public static void init(int num, int start, int end){ //초기화하는 거
40+
if(start==end){
41+
tree[num] = arr[start];
42+
}else{
43+
init(num*2, start, (start+end)/2);
44+
init(num*2 + 1,(start+end)/2 + 1, end);
45+
tree[num] = tree[num*2] + tree[num*2+1];
46+
}
47+
}
48+
public static long query(int num, int start, int end, int left, int right){ //구간 합
49+
if(right<start || left>end){//구하려는 구간내에 현재 범위가 없어.
50+
return 0;
51+
}else if(left<=start && right>=end){//구하려는 구간내에 현재 범위가 있어. 다 더해야겟지
52+
return tree[num];
53+
}
54+
long lsum = query(num*2, start, (start+end)/2, left, right);
55+
long rsum = query(num*2+1, (start+end)/2 + 1, end, left, right);
56+
return lsum + rsum;
57+
}
58+
public static void update(int num, int start, int end, int index, long diff){// 수정
59+
if(start>index || end<index) return; //현재 위치가 수정할 곳과 연관이 있는가?
60+
tree[num] += diff; // 있으니 변화량 반영
61+
62+
if(start != end){//현재 위치가 리프노드인가? 그렇다면 이미 반영이 되었고 아니라면 재귀적으로 반영해야함.
63+
update(num*2, start,(start+end)/2,index,diff);
64+
update(num*2+1,(start+end)/2 + 1,end,index,diff);
65+
}
66+
}
67+
}
68+
```

0 commit comments

Comments
 (0)