ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 14288 |
문제명 | 회사 문화 4 |
레벨 | 플래티넘 3 |
분류 |
구간 쿼리 |
시간복잡도 | O(n+mlogn) |
인풋사이즈 | n<=100,000, m<=100,000 |
사용한 언어 | Python |
제출기록 | 64496KB / 764ms |
최고기록 | 764ms |
해결날짜 | 2021/04/30 |
"""Solution code for "BOJ 14288. 회사 문화 4".
- Problem link: https://www.acmicpc.net/problem/14288
- Solution link: http://www.teferi.net/ps/problems/boj/14288
"""
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_for_upward = fenwicktree.FenwickTree(n + 1)
fenwick_for_downward = fenwicktree.FenwickTree(n + 1)
is_downward = True
for _ in range(m):
query = [int(x) for x in sys.stdin.readline().split()]
if query[0] == 1:
_, i, w = query
beg, end = subtree_ranges[i - 1]
if is_downward:
fenwick_for_downward.update(beg, w)
fenwick_for_downward.update(end, -w)
else:
fenwick_for_upward.update(beg, w)
elif query[0] == 2:
i = query[1]
beg, end = subtree_ranges[i - 1]
print(fenwick_for_downward.query(0, beg + 1)
+ fenwick_for_upward.query(beg, end))
else:
is_downward = not is_downward
if __name__ == '__main__':
main()