Created
April 17, 2016 07:17
-
-
Save mikezhuyuan/90cfb984eb2f736c704b37389f79c64b to your computer and use it in GitHub Desktop.
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 find_max_circle(next_items): | |
visited = {} | |
max_circle = 0 | |
for current in next_items: | |
if current in visited: | |
continue | |
path = [] | |
p = current | |
while p not in visited: | |
path.append(p) | |
visited[p] = True | |
p = next_items[p] | |
if p in path: | |
circle = len(path) - path.index(p) | |
max_circle = max(max_circle, circle) | |
return max_circle | |
def find_tree_height(node, root, node_children, exclude=None): | |
if node is None or node == exclude: | |
return 0 | |
max_child_height = 0 | |
for child in node_children[node]: | |
if child is not root: | |
max_child_height = max(max_child_height, find_tree_height(child, root, node_children, exclude)) | |
return 1 + max_child_height | |
def get_node_children(next_items): | |
node_children = [] | |
for current in range(len(next_items)): | |
children = [] | |
for child, parent in enumerate(next_items): | |
if parent == current: | |
children.append(child) | |
node_children.append(children) | |
return node_children | |
def get_partitions(next_items): | |
for current, depends_on in enumerate(next_items): | |
if current == next_items[depends_on]: | |
if current < depends_on: | |
yield (current, depends_on) | |
def get_total_partition_width(next_items): | |
node_children = get_node_children(next_items) | |
partitions = get_partitions(next_items) | |
total = 0 | |
for partition in partitions: | |
total += find_tree_height(partition[0], partition[0], node_children, partition[1]) | |
total += find_tree_height(partition[1], partition[1], node_children, partition[0]) | |
return total | |
def solve(items): | |
return max(find_max_circle(items), get_total_partition_width(items)) | |
file = open('input3a') | |
index = 0 | |
for line in file.readlines(): | |
if index != 0 and index % 2 == 0: | |
answer = solve([int(s) - 1 for s in line.strip().split()]) | |
print('Case #%s: %i' % (index // 2, answer)) | |
index += 1 | |
file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment