본문 바로가기
알고리즘

Segment Tree

by 이재현9999 2024. 10. 11.
import sys
input = sys.stdin.readline

N, M, K = map(int, input().split())

arr = []
for _ in range(N):
    arr.append(int(input()))

tree = [0] * (4 * N)
minTree = [0] * (4 * N)
maxTree = [0] * (4 * N)

def init(node, start, end):
    if start == end:
        tree[node] = arr[start]
        return

    mid = (start + end) // 2
    init(2 * node, start, mid)
    init(2 * node + 1, mid + 1, end)
    tree[node] = tree[2 * node] + tree[2 * node + 1]

def min_init(node, start, end):
    if start == end:
        minTree[node] = arr[start]
        return

    mid = (start + end) // 2
    min_init(2 * node, start, mid)
    min_init(2 * node + 1, mid + 1, end)
    minTree[node] = min(minTree[2 * node], minTree[2 * node + 1])

def max_init(node, start, end):
    if start == end:
        maxTree[node] = arr[start]
        return

    mid = (start + end) // 2
    max_init(2 * node, start, mid)
    max_init(2 * node + 1, mid + 1, end)
    maxTree[node] = max(maxTree[2 * node], maxTree[2 * node + 1])

init(1, 0, N-1)

def update(node, start, end, idx, diff):
    if idx < start or end < idx:
        return

    tree[node] += diff

    if start != end:
        mid = (start + end) // 2
        update(2 * node, start, mid, idx, diff)
        update(2 * node + 1, mid + 1, end, idx, diff)

def query(node, start, end, left, right):
    if right < start or end < left:
        return 0

    if left <= start and end <= right:
        return tree[node]

    mid = (start + end) // 2
    q1 = query(2 * node, start, mid, left, right)
    q2 = query(2 * node + 1, mid + 1, end, left, right)
    return q1 + q2 

def min_query(node, start, end, left, right):
    if right < start or end < left:
        return float('INF')

    if left <= start and end <= right:
        return minTree[node]

    mid = (start + end) // 2
    q1 = min_query(2 * node, start, mid, left, right)
    q2 = min_query(2 * node + 1, mid + 1, end, left, right)
    return min(q1, q2)

def max_query(node, start, end, left, right):
    if right < start or end < left:
        return 0
    
    if left <= start and end <= right:
        return maxTree[node]
    
    mid = (start + end) // 2
    q1 = max_query(2 * node, start, mid, left, right)
    q2 = max_query(2 * node + 1, mid + 1, end, left, right)
    return max(q1, q2)

for _ in range(M+K):
    a, b, c = map(int, input().split())
    b -= 1
    if a == 1:
        diff = c - arr[b]
        arr[b] = c
        update(1, 0, N-1, b, diff)
    elif a == 2:
        c -= 1
        print(query(1, 0, N-1, b, c))

'알고리즘' 카테고리의 다른 글

Prefix Sum, Prefix Sum of Matrix  (0) 2024.10.11
Topology Sort  (0) 2024.10.11
Floyd-Warshall  (0) 2024.10.11
Dijkstra  (0) 2024.10.11
Bellman-Ford  (0) 2024.10.11