Skip to content

Commit 407ccae

Browse files
author
Hamid Gasmi
committed
#149 is completed: dynammic programming technique + DFS traversal
1 parent a4829d5 commit 407ccae

File tree

1 file changed

+35
-17
lines changed

1 file changed

+35
-17
lines changed

4-np-complete-problems/2-coping_with_np_completeness/plan_fun_party.py

+35-17
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
#uses python3
21
import sys
32
import threading
43

@@ -16,40 +15,59 @@ def __init__(self, size, weights, edges):
1615
self.build_children_list(edges)
1716

1817
def build_children_list(self, edges):
19-
2018
self.children_list = [[] for _ in range(self.size)]
2119
for p, c in edges:
2220
self.children_list[p - 1].append(c - 1)
2321
self.children_list[c - 1].append(p - 1)
2422

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]
2939

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
3343

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:
3754
return 0
38-
#dfs(tree, 0, -1)
39-
# You must decide what to return.
40-
return 0
4155

56+
total_weight = [0] * tree.size
57+
tree.total_weight_dfs(0, -1, total_weight)
58+
59+
return total_weight[0]
4260

4361
def main():
4462

4563
size = int(input())
4664
weights = [w for w in map(int, input().split())]
4765
edges = []
48-
for i in range(1, size):
66+
for _ in range(1, size):
4967
edges.append(list(map(int, input().split())))
5068
tree = Tree(size, weights, edges)
5169

52-
weight = MaxWeightIndependentTreeSubset(size)
70+
weight = MaxWeightIndependentTreeSubset(tree)
5371
print(weight)
5472

5573
if __name__ == "__main__":

0 commit comments

Comments
 (0)