1
1
#uses python3
2
-
3
2
import sys
4
3
import threading
5
4
6
- # This code is used to avoid stack overflow issues
7
- sys .setrecursionlimit (10 ** 6 ) # max depth of recursion
8
- threading .stack_size (2 ** 26 ) # new thread will get stack of such size
9
-
10
-
11
- class Vertex :
12
- def __init__ (self , weight ):
13
- self .weight = weight
14
- self .children = []
15
-
16
-
17
- def ReadTree ():
18
- size = int (input ())
19
- tree = [Vertex (w ) for w in map (int , input ().split ())]
20
- for i in range (1 , size ):
21
- a , b = list (map (int , input ().split ()))
22
- tree [a - 1 ].children .append (b - 1 )
23
- tree [b - 1 ].children .append (a - 1 )
24
- return tree
25
-
5
+ # This problem can be reduced to Independent Set problem (ISP) which is an NP problem
6
+ # It's a special case of ISP
7
+ # It's can be solved effeciently with Dynamic Programming technique:
8
+ # Let's W(v) reprensents the Total Fun (weight) in the party, then:
9
+ # F(v) = Max(weight(v) + sum(weight(u) for all u grand-children of v),
10
+ # sum(weight(u) for all u children of v))
11
+
12
+ class Tree :
13
+ def __init__ (self , size , weights , edges ):
14
+ self .size = size
15
+ self .weights = weights .copy ()
16
+ self .build_children_list (edges )
17
+
18
+ def build_children_list (self , edges ):
19
+
20
+ self .children_list = [[] for _ in range (self .size )]
21
+ for p , c in edges :
22
+ self .children_list [p - 1 ].append (c - 1 )
23
+ self .children_list [c - 1 ].append (p - 1 )
26
24
27
25
def dfs (tree , vertex , parent ):
28
26
for child in tree [vertex ].children :
@@ -33,21 +31,32 @@ def dfs(tree, vertex, parent):
33
31
# Write your code here.
34
32
# You may need to add more parameters to this function for child processing.
35
33
36
-
37
- def MaxWeightIndependentTreeSubset (tree ):
38
- size = len (tree )
34
+ def MaxWeightIndependentTreeSubset (size ):
35
+ #size = len(tree)
39
36
if size == 0 :
40
37
return 0
41
- dfs (tree , 0 , - 1 )
38
+ # dfs(tree, 0, -1)
42
39
# You must decide what to return.
43
40
return 0
44
41
45
42
46
43
def main ():
47
- tree = ReadTree ();
48
- weight = MaxWeightIndependentTreeSubset (tree );
44
+
45
+ size = int (input ())
46
+ weights = [w for w in map (int , input ().split ())]
47
+ edges = []
48
+ for i in range (1 , size ):
49
+ edges .append (list (map (int , input ().split ())))
50
+ tree = Tree (size , weights , edges )
51
+
52
+ weight = MaxWeightIndependentTreeSubset (size )
49
53
print (weight )
50
54
55
+ if __name__ == "__main__" :
56
+
57
+ # To avoid stack overflow issues
58
+ sys .setrecursionlimit (10 ** 6 ) # max depth of recursion
59
+ threading .stack_size (2 ** 26 ) # new thread will get stack of such size
51
60
52
- # This is to avoid stack overflow issues
53
- threading .Thread (target = main ).start ()
61
+ # This is to avoid stack overflow issues
62
+ threading .Thread (target = main ).start ()
0 commit comments