Hanbit the Developer

[Python] 백준 2042번: 구간 합 구하기(using fenwick-tree) 본문

Algorithm/백준

[Python] 백준 2042번: 구간 합 구하기(using fenwick-tree)

hanbikan 2021. 10. 8. 21:07

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
input = sys.stdin.readline


def update_fenwick_tree(tree, index, value):
    while index < len(tree):
        tree[index] += value
        index += (index & -index)

    return tree


def query_fenwick_tree(tree, index):
    res = 0
    while index > 0:
        res += tree[index]
        index -= (index & -index)

    return res


if __name__ == '__main__':
    N, M, K = map(int, input().split())

    tree = [0]*(N+1)
    nums = [int(input()) for _ in range(N)]
    for i in range(N):
        tree = update_fenwick_tree(tree, i+1, nums[i])

    for _ in range(M + K):
        a, b, c = map(int, input().split())

        if a == 1:
            tree = update_fenwick_tree(tree, b, c - nums[b-1])
            nums[b-1] = c
        elif a == 2:
            print(query_fenwick_tree(tree, c) - query_fenwick_tree(tree, b-1))

 

펜윅트리에 대한 설명은 아래 링크에 너무나도 잘 되어있다.

 

https://www.acmicpc.net/blog/view/21

 

펜윅 트리 (바이너리 인덱스 트리)

블로그: 세그먼트 트리 (Segment Tree) 에서 풀어본 문제를 Fenwick Tree를 이용해서 풀어보겠습니다. Fenwick Tree는 Binary Indexed Tree라고도 하며, 줄여서 BIT라고 합니다. Fenwick Tree를 구현하려면, 어떤 수 X

www.acmicpc.net

 

 

 

펜윅트리를 구현한 뒤, update만 좀 신경써주면 된다. update는 값을 더하는 것이 기본이기 때문에, 가령 3을 7로 바꿔야한다고 하면 4를 인자로 넣어주는 것이다.

업데이트를 마친 뒤 nums(입력 받은 값, 트리가 아님)에 바뀐 값(7)을 넣어주어야한다.