1
- #uses python3
2
1
import sys
3
2
import threading
4
3
@@ -16,40 +15,59 @@ def __init__(self, size, weights, edges):
16
15
self .build_children_list (edges )
17
16
18
17
def build_children_list (self , edges ):
19
-
20
18
self .children_list = [[] for _ in range (self .size )]
21
19
for p , c in edges :
22
20
self .children_list [p - 1 ].append (c - 1 )
23
21
self .children_list [c - 1 ].append (p - 1 )
24
22
25
- def dfs (tree , vertex , parent ):
26
- for child in tree [vertex ].children :
27
- if child != parent :
28
- dfs (tree , child , vertex )
23
+ def total_weight_dfs (self , v , parent , total_weight ):
24
+
25
+ if total_weight [v ] > 0 :
26
+ return
27
+
28
+ if len (self .children_list [v ]) == 0 :
29
+ total_weight [v ] = self .weights [v ]
30
+
31
+ children_weight = 0
32
+ grand_children_weight = 0
33
+ for child in self .children_list [v ]:
34
+ if child == parent :
35
+ continue
36
+
37
+ self .total_weight_dfs (child , v , total_weight )
38
+ children_weight += total_weight [child ]
29
39
30
- # This is a template function for processing a tree using depth-first search.
31
- # Write your code here.
32
- # You may need to add more parameters to this function for child processing.
40
+ for grand_child in self . children_list [ child ]:
41
+ if grand_child == v :
42
+ continue
33
43
34
- def MaxWeightIndependentTreeSubset (size ):
35
- #size = len(tree)
36
- if size == 0 :
44
+ grand_children_weight += total_weight [grand_child ]
45
+
46
+ if self .weights [v ] + grand_children_weight < children_weight :
47
+ total_weight [v ] = children_weight
48
+ else :
49
+ total_weight [v ] = self .weights [v ] + grand_children_weight
50
+
51
+ def MaxWeightIndependentTreeSubset (tree ):
52
+
53
+ if tree .size == 0 :
37
54
return 0
38
- #dfs(tree, 0, -1)
39
- # You must decide what to return.
40
- return 0
41
55
56
+ total_weight = [0 ] * tree .size
57
+ tree .total_weight_dfs (0 , - 1 , total_weight )
58
+
59
+ return total_weight [0 ]
42
60
43
61
def main ():
44
62
45
63
size = int (input ())
46
64
weights = [w for w in map (int , input ().split ())]
47
65
edges = []
48
- for i in range (1 , size ):
66
+ for _ in range (1 , size ):
49
67
edges .append (list (map (int , input ().split ())))
50
68
tree = Tree (size , weights , edges )
51
69
52
- weight = MaxWeightIndependentTreeSubset (size )
70
+ weight = MaxWeightIndependentTreeSubset (tree )
53
71
print (weight )
54
72
55
73
if __name__ == "__main__" :
0 commit comments