목차

회사 문화 3

ps
링크acmicpc.net/…
출처BOJ
문제 번호14287
문제명회사 문화 3
레벨플래티넘 4
분류

구간 쿼리

시간복잡도O(n+mlogn)
인풋사이즈n<=100,000, m<=100,000
사용한 언어Python
제출기록59384KB / 704ms
최고기록704ms
해결날짜2021/04/30

풀이

코드

"""Solution code for "BOJ 14287. 회사 문화 3".

- Problem link: https://www.acmicpc.net/problem/14287
- Solution link: http://www.teferi.net/ps/problems/boj/14287
"""

import sys
from teflib import fenwicktree
from teflib import tgraph


def euler_tour_technique(tree, root):
    subtree_ranges = [[None, None] for _ in tree]
    order = 0
    for node in tgraph.dfs(tree, root, yields_on_leave=True):
        if subtree_ranges[node][0] is None:
            subtree_ranges[node][0] = order
            order += 1
        else:
            subtree_ranges[node][1] = order
    return subtree_ranges


def main():
    n, m = [int(x) for x in sys.stdin.readline().split()]
    tree = [[] for _ in range(n)]
    bosses = [int(x) for x in sys.stdin.readline().split()]
    for employee, boss in enumerate(bosses):
        if boss != -1:
            tree[boss - 1].append(employee)
    subtree_ranges = euler_tour_technique(tree, 0)
    fenwick = fenwicktree.FenwickTree(n + 1)
    for _ in range(m):
        query = [int(x) for x in sys.stdin.readline().split()]
        if query[0] == 1:
            _, i, w = query
            fenwick.update(subtree_ranges[i - 1][0], w)
        else:
            i = query[1]            
            print(fenwick.query(*subtree_ranges[i - 1]))


if __name__ == '__main__':
    main()