Skip to content

Commit 72a010c

Browse files
authored
Create 2322. Minimum Score After Removals on a Tree.py
1 parent 7f0b46f commit 72a010c

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
class Solution:
2+
def minimumScore(self, nums: list[int], edges: list[list[int]]) -> int:
3+
n = len(nums)
4+
5+
graph = [[] for _ in range(n)]
6+
7+
for a, b in edges:
8+
graph[a].append(b)
9+
graph[b].append(a)
10+
11+
sub_xor = [0] * n
12+
tin = [0] * n
13+
tout = [0] * n
14+
15+
time = 0
16+
17+
def dfs(node, parent):
18+
nonlocal time
19+
20+
tin[node] = time
21+
time += 1
22+
23+
xor_value = nums[node]
24+
25+
for nxt in graph[node]:
26+
if nxt == parent:
27+
continue
28+
29+
dfs(nxt, node)
30+
xor_value ^= sub_xor[nxt]
31+
32+
sub_xor[node] = xor_value
33+
34+
tout[node] = time
35+
time += 1
36+
37+
dfs(0, -1)
38+
39+
total = sub_xor[0]
40+
41+
def is_ancestor(a, b):
42+
return tin[a] <= tin[b] and tout[b] <= tout[a]
43+
44+
ans = float("inf")
45+
46+
# node i는
47+
# parent(i) - i 간선을 자른다는 의미
48+
#
49+
# root(0)는 부모 간선이 없으므로 제외
50+
for a in range(1, n):
51+
for b in range(a + 1, n):
52+
53+
if is_ancestor(a, b):
54+
# a 안에 b가 존재
55+
x1 = sub_xor[b]
56+
x2 = sub_xor[a] ^ sub_xor[b]
57+
x3 = total ^ sub_xor[a]
58+
59+
elif is_ancestor(b, a):
60+
# b 안에 a가 존재
61+
x1 = sub_xor[a]
62+
x2 = sub_xor[b] ^ sub_xor[a]
63+
x3 = total ^ sub_xor[b]
64+
65+
else:
66+
# 서로 독립된 subtree
67+
x1 = sub_xor[a]
68+
x2 = sub_xor[b]
69+
x3 = total ^ sub_xor[a] ^ sub_xor[b]
70+
71+
score = max(x1, x2, x3) - min(x1, x2, x3)
72+
ans = min(ans, score)
73+
74+
return ans

0 commit comments

Comments
 (0)