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
-
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))
10
11
11
12
class Vertex :
12
13
def __init__ (self , weight ):
13
14
self .weight = weight
14
15
self .children = []
15
16
17
+ class Tree :
18
+ def __init__ (self , size , weights ):
19
+ self .size = size
20
+ self .weights = [weights [i ] for i in range (size )]
16
21
22
+
17
23
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
-
24
+
25
+
26
26
27
27
def dfs (tree , vertex , parent ):
28
28
for child in tree [vertex ].children :
@@ -44,10 +44,25 @@ def MaxWeightIndependentTreeSubset(tree):
44
44
45
45
46
46
def main ():
47
- tree = ReadTree ();
48
- weight = MaxWeightIndependentTreeSubset (tree );
47
+ tree = ReadTree ()
48
+ weight = MaxWeightIndependentTreeSubset (tree )
49
49
print (weight )
50
50
51
+ if __name__ == "__main__" :
52
+
53
+ # To avoid stack overflow issues
54
+ sys .setrecursionlimit (10 ** 6 ) # max depth of recursion
55
+ threading .stack_size (2 ** 26 ) # new thread will get stack of such size
56
+
57
+ size = int (input ())
58
+ weights = map (int , input ().split ())
59
+ print (weights )
60
+ #tree = [Vertex(w) for w in map(int, input().split())]
61
+ #for i in range(1, size):
62
+ # a, b = list(map(int, input().split()))
63
+ # tree[a - 1].children.append(b - 1)
64
+ # tree[b - 1].children.append(a - 1)
65
+ #return tree
51
66
52
- # This is to avoid stack overflow issues
53
- threading .Thread (target = main ).start ()
67
+ # This is to avoid stack overflow issues
68
+ # threading.Thread(target=main).start()
0 commit comments