-
-
Save jakab922/4e7b34080eca8ce09af6 to your computer and use it in GitHub Desktop.
190/2/E
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
n = int(raw_input().strip()) | |
letters = [chr(x) for x in xrange(65, 91)] | |
cl = 0 | |
graph = [set() for _ in xrange(n)] | |
for i in xrange(n - 1): | |
x, y = map(int, raw_input().strip().split(' ')) | |
x-=1; y-=1 | |
graph[x].add(y) | |
graph[y].add(x) | |
ranks = map(len, graph) | |
def find_centrum(nodes): | |
""" Finds girth centrum of the graph and return the central nodes and the subtrees we get by taking out the central node(s). """ | |
ln = len(nodes) | |
cleafs = set([i for i in nodes if len(graph[i]) <= 1]) | |
needed = ln | |
modifiers = {} | |
was = set(x for x in cleafs) | |
while cleafs: | |
if len(cleafs) == needed: | |
break | |
else: | |
nleafs = set() | |
for leaf in cleafs: | |
maybe_parents = [x for x in graph[leaf] if x not in was] | |
if maybe_parents: # for leaf-parent-leaf types | |
parent = maybe_parents[0] | |
if parent in modifiers: | |
modifiers[parent] += 1 | |
else: | |
modifiers[parent] = 1 | |
if ranks[parent] - modifiers[parent] == 1: | |
nleafs.add(parent) | |
was.add(parent) | |
needed -= len(cleafs) | |
cleafs = nleafs | |
center = cleafs.pop() | |
ranks[center] = 0 | |
tree_starters = [x for x in graph[center]] | |
for neighbor in graph[center]: | |
graph[neighbor].remove(center) | |
ranks[neighbor] -= 1 | |
graph[center] = set() | |
subtrees = [0 for _ in xrange(len(tree_starters))] | |
for i, node in enumerate(tree_starters): | |
subtree = set([node]) | |
stack = set([node]) | |
while stack: | |
cnode = stack.pop() | |
for neighbor in graph[cnode]: | |
if neighbor not in subtree: | |
subtree.add(neighbor) | |
stack.add(neighbor) | |
subtrees[i] = subtree | |
return (center, subtrees) | |
forest = [range(n)] | |
assignments = ["A" for _ in range(n)] | |
while forest: | |
if cl == len(letters): | |
print "Impossible!" | |
exit() | |
nforest = [] | |
for tree in forest: | |
center, subtrees = find_centrum(tree) | |
assignments[center] = letters[cl] | |
nforest.extend(subtrees) | |
cl += 1 | |
forest = nforest | |
print " ".join(assignments) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment