[Gold I] Title: 구간 합 구하기, Time: 1152 ms, Memory: 119452 KB -BaekjoonHub

This commit is contained in:
SSUM
2025-03-03 17:52:05 +09:00
parent d69d79709a
commit 6b7404f2b2
2 changed files with 82 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
# [Gold I] 구간 합 구하기 - 2042
[문제 링크](https://www.acmicpc.net/problem/2042)
### 성능 요약
메모리: 119452 KB, 시간: 1152 ms
### 분류
세그먼트 트리, 자료 구조
### 제출 일자
2025년 3월 3일 17:51:46
### 문제 설명
<p>어떤 N개의 수가 주어져 있다. 그런데 중간에 수의 변경이 빈번히 일어나고 그 중간에 어떤 부분의 합을 구하려 한다. 만약에 1,2,3,4,5 라는 수가 있고, 3번째 수를 6으로 바꾸고 2번째부터 5번째까지 합을 구하라고 한다면 17을 출력하면 되는 것이다. 그리고 그 상태에서 다섯 번째 수를 2로 바꾸고 3번째부터 5번째까지 합을 구하라고 한다면 12가 될 것이다.</p>
### 입력
<p>첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000,000)과 M(1 ≤ M ≤ 10,000), K(1 ≤ K ≤ 10,000) 가 주어진다. M은 수의 변경이 일어나는 횟수이고, K는 구간의 합을 구하는 횟수이다. 그리고 둘째 줄부터 N+1번째 줄까지 N개의 수가 주어진다. 그리고 N+2번째 줄부터 N+M+K+1번째 줄까지 세 개의 정수 a, b, c가 주어지는데, a가 1인 경우 b(1 ≤ b ≤ N)번째 수를 c로 바꾸고 a가 2인 경우에는 b(1 ≤ b ≤ N)번째 수부터 c(b ≤ c ≤ N)번째 수까지의 합을 구하여 출력하면 된다.</p>
<p>입력으로 주어지는 모든 수는 -2<sup>63</sup>보다 크거나 같고, 2<sup>63</sup>-1보다 작거나 같은 정수이다.</p>
### 출력
<p>첫째 줄부터 K줄에 걸쳐 구한 구간의 합을 출력한다. 단, 정답은 -2<sup>63</sup>보다 크거나 같고, 2<sup>63</sup>-1보다 작거나 같은 정수이다.</p>

View File

@@ -0,0 +1,52 @@
import sys
input = sys.stdin.readline
n, m, k = map(int, input().split()) # 수의 개수, 변경 횟수, 구간 합 횟수
leafnodeV = n
height = 0
while leafnodeV!=0:
leafnodeV//=2
height+=1
tree = [0]*pow(2, height+1)
start_tree_index = pow(2, height) - 1
tree_size = pow(2, height+1)
for i in range(start_tree_index+1, start_tree_index+n+1):
tree[i] = int(input())
temp = tree_size - 1
while temp!=1:
tree[temp//2] += tree[temp]
temp -= 1
def change_val(index, value):
diff = value - tree[index]
while(index > 0):
tree[index] = tree[index] + diff
index //= 2
def get_sum(s,e):
partSum = 0
while s<=e:
if s%2==1:
partSum += tree[s]
s += 1
if e%2==0:
partSum+= tree[e]
e -= 1
s //= 2
e //= 2
return partSum
for _ in range(m+k):
event, s, e = map(int, input().split())
if event == 1:
change_val(start_tree_index+s, e)
else:
s = start_tree_index + s
e = start_tree_index + e
print(get_sum(s, e))