Skip to content

Instantly share code, notes, and snippets.

/even-tree.py Secret

Created December 20, 2016 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7effb6529c43bf752711f1f7aeadbe4f to your computer and use it in GitHub Desktop.
Save anonymous/7effb6529c43bf752711f1f7aeadbe4f to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from treelib import Node, Tree
ROOT = 1
# Read the tree
tree = Tree()
tree.create_node(ROOT, ROOT, data=1) # data means weight
n, m = 0, 0
for line in sys.stdin:
u, v = [int(x) for x in line.split()]
if n == 0: # Process the first line
n, m = u, v
else:
if tree.contains(int(u)):
tree.create_node(v, v, parent=u, data=1)
elif tree.contains(int(v)):
tree.create_node(u, u, parent=v, data=1)
# Process the tree
edges_removed = 0
while tree.depth() > 0:
for leaf in tree.leaves(ROOT):
leaf_id = leaf.identifier
parent = tree.parent(leaf_id)
# If the total weigth is even, we can cut this edge
if leaf.data % 2 == 0:
edges_removed += 1
# Glue the leaves to their parents, making them heavier
# (Cutting does not affect the parity)
parent.data += leaf.data
tree.remove_node(leaf_id)
# Output the result
print edges_removed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment