Skip to content

Commit 7e9519c

Browse files
committed
docs: 세그먼트 트리 예시 추가
1 parent 9b3787e commit 7e9519c

File tree

1 file changed

+78
-1
lines changed

1 file changed

+78
-1
lines changed

_posts/2024-05-21-segment-tree.md

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,84 @@ console.log(query(3, 5, 1, 0, arr.length - 1)); // 8 + 9 + 11 = 28
286286

287287
## Example
288288

289-
- <a href="" target="_blank">TODO</a>
289+
- <a href="https://www.acmicpc.net/problem/11505" target="_blank">11505번: 구간 곱 구하기</a>
290+
291+
```javascript
292+
const path = process.platform === "linux" ? "/dev/stdin" : "input.txt";
293+
const input = require("fs").readFileSync(path).toString().split("\n");
294+
295+
// N: 수의 개수, 1 <= N <= 1_000_000
296+
// M: 수의 변경이 일어나는 횟수, 1 <= M <= 10_000
297+
// K: 구간 곱을 구하는 횟수, 1 <= K <= 10_000
298+
const [N, M, K] = input[0].split(" ").map(Number);
299+
const MOD = 1_000_000_007n;
300+
const arr = [];
301+
302+
for (let i = 1; i <= N; i++) {
303+
arr.push(Number(input[i]));
304+
}
305+
306+
const tree = Array(arr.length * 4);
307+
308+
const init = (left, right, node) => {
309+
if (left === right) {
310+
tree[node] = BigInt(arr[left]);
311+
return;
312+
}
313+
314+
const mid = Math.floor((left + right) / 2);
315+
init(left, mid, node * 2);
316+
init(mid + 1, right, node * 2 + 1);
317+
tree[node] = (tree[node * 2] * tree[node * 2 + 1]) % MOD;
318+
};
319+
320+
const query = (left, right, node, nodeLeft, nodeRight) => {
321+
if (right < nodeLeft || nodeRight < left) {
322+
return 1n;
323+
}
324+
325+
if (left <= nodeLeft && nodeRight <= right) {
326+
return tree[node];
327+
}
328+
329+
const mid = Math.floor((nodeLeft + nodeRight) / 2);
330+
const leftResult = query(left, right, node * 2, nodeLeft, mid);
331+
const rightResult = query(left, right, node * 2 + 1, mid + 1, nodeRight);
332+
return (leftResult * rightResult) % MOD;
333+
};
334+
335+
const update = (index, newValue, node, nodeLeft, nodeRight) => {
336+
if (index < nodeLeft || nodeRight < index) {
337+
return;
338+
}
339+
340+
if (nodeLeft === nodeRight) {
341+
tree[node] = BigInt(newValue);
342+
return;
343+
}
344+
345+
const mid = Math.floor((nodeLeft + nodeRight) / 2);
346+
update(index, newValue, node * 2, nodeLeft, mid);
347+
update(index, newValue, node * 2 + 1, mid + 1, nodeRight);
348+
tree[node] = (tree[node * 2] * tree[node * 2 + 1]) % MOD;
349+
};
350+
351+
init(0, arr.length - 1, 1);
352+
353+
let answer = "";
354+
355+
for (let i = N + 1; i < N + M + K + 1; i++) {
356+
const [a, b, c] = input[i].split(" ").map(Number);
357+
358+
if (a === 1) {
359+
update(b - 1, c, 1, 0, arr.length - 1);
360+
} else {
361+
answer += `${query(b - 1, c - 1, 1, 0, arr.length - 1)}\n`;
362+
}
363+
}
364+
365+
console.log(answer.trim());
366+
```
290367

291368
## 참고 자료
292369

0 commit comments

Comments
 (0)