https://www.acmicpc.net/problem/2042
2042번: 구간 합 구하기
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000,000)과 M(1 ≤ M ≤ 10,000), K(1 ≤ K ≤ 10,000) 가 주어진다. M은 수의 변경이 일어나는 횟수이고, K는 구간의 합을 구하는 횟수이다. 그리고 둘째 줄부터 N+1번째 줄
www.acmicpc.net
문제 접근
세그먼트 트리로 쉽게 풀렸다.
구간 합을 세그먼트 트리의 각 노드에 적으면서 올라가면 쉽게 풀린다.
코드
import sys
import math
input = sys.stdin.readline
"""
1.
"""
N, M, K = map(int, input().split())
node = 2**math.ceil(math.log2(N))
tree = [0 for i in range(node * 2 + 1)]
a, b, c = 0, 0, 0
for n in range(N):
tree[node + n] = int(input())
def init(index):
if index >= node:
return tree[index]
tree[index] = init(index * 2) + init(index * 2 + 1)
return tree[index]
def update(index):
tree[index] = c
while index > 1:
tree[index // 2] = tree[index] + (tree[index + 1] if index %
2 == 0 else tree[index - 1])
index = index // 2
def ans(start, end, index):
if end < b or start > c:
return 0
if b<= start and end <= c:
return tree[index]
mid = (start + end) // 2
return ans(start, mid, index * 2) + ans(mid + 1, end, index * 2 + 1)
init(1)
for _ in range(M + K):
a, b, c = map(int, input().split())
if a == 1:
b = b + node - 1
update(b)
else:
print(ans(1, node, 1))
'백준 > 문제풀이_python' 카테고리의 다른 글
2243 사탕상자 python (0) | 2024.02.04 |
---|---|
10999 구간 합 구하기 2 python (0) | 2024.02.04 |
13537 수열과 쿼리 1 python (0) | 2024.02.01 |
14427 수열과 쿼리 15 (0) | 2024.01.31 |
16637 괄호 추가하기 (0) | 2024.01.24 |
댓글