-
Notifications
You must be signed in to change notification settings - Fork 1
/
max_weight_independent_set.py
61 lines (51 loc) · 1.74 KB
/
max_weight_independent_set.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#uses python3
import sys
import threading
# This code is used to avoid stack overflow issues
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**26) # new thread will get stack of such size
class Vertex:
def __init__(self, weight):
self.children = []
self.weight = weight
def Read_Tree():
size = int(input())
tree = [Vertex(weight) for weight in map(int, input().split())]
for i in range(1, size):
a, b = list(map(int, input().split()))
tree[a - 1].children.append(b - 1)
tree[b - 1].children.append(a - 1)
return tree
def dfs(tree, vertex, parent, D):
# This is a template function for processing a tree using depth-first search.
# Write your code here.
# You may need to add more parameters to this function for child processing.
if -1 == D[vertex]:
if 1 == len(tree[vertex].children) and 0 != vertex:
D[vertex] = tree[vertex].weight
else:
m1 = tree[vertex].weight
for u in tree[vertex].children:
if u != parent:
for w in tree[u].children:
if w != vertex:
m1 += dfs(tree, w, u, D)
m0 = 0
for u in tree[vertex].children:
if u != parent:
m0 += dfs(tree, u, vertex, D)
D[vertex] = max(m1, m0)
return D[vertex]
def MaxWeightIndependentTreeSubset(tree):
size = len(tree)
if size == 0:
return 0
D = [-1] * size
d = dfs(tree, 0, -1, D)
return d
def main():
tree = Read_Tree()
weight = MaxWeightIndependentTreeSubset(tree)
print(weight)
# This is to avoid stack overflow issues
threading.Thread(target=main).start()