Last active
December 30, 2015 05:39
-
-
Save pixyj/7784024 to your computer and use it in GitHub Desktop.
Max weight independent set of a path graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def max_weights(a): | |
weights = [0] * (len(a) + 2) | |
for i, v in enumerate(a): | |
j = i + 2 | |
with_v = weights[j-2] + v | |
without_v = weights[j-1] | |
weights[j] = max(with_v, without_v) | |
return weights | |
def max_weight_independent_set(a): | |
weights = max_weights(a) | |
elements = [] | |
j = len(weights) - 1 | |
while j > 1: | |
i = j - 2 | |
if weights[j] - weights[j-2] == a[i]: | |
elements.append(a[i]) | |
j -= 2 | |
else: | |
j -= 1 | |
elements.reverse() | |
return elements | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment