## Editorial for DMOPC '19 Contest 1 P4 - A Strange Graph

Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Author: george_chen

For the first subtask, it suffices to generate all strings of length and check if they will form the given graph.

Time complexity:

The second subtask is just a simpler case of the full solution. To solve it we must make an observation about this graph.
Let be the set of neighbours of node . Let . Then we have that if for two nodes and that then . Therefore, we can generate for each of the nodes in the graph and we will know which characters are equal.

Since the graph is a tree, we observe that none of the will be equal so each node must represent a distinct character with the exception of a connected component consisting of exactly nodes. We observe that in this special case, the two nodes can be assigned the same letter. It follows that there can be no more than nodes in the input otherwise the answer is just -1. Additionally, observe that each node can only be adjacent to at most other nodes since each character in the alphabet is adjacent to exactly other letters. Combining these observations, we realize that the graph will be composed of a single chain which we can perform depth first search on to assign letters.

Time complexity:

For the final subtask, we will generalize the observation from subtask 2. Observe that if two nodes have , it is always optimal to assign as we take up less characters in the alphabet. After calculating for all the nodes, we try to assign an id to each distinct . If there are more than such groups, then the answer is -1 since there are only letters in the alphabet. After this is done, we compress all nodes in the graph that have the same into one node while maintaining the edges between nodes. The resulting compressed graph has at most nodes that represent a group of nodes that should be assigned the same letter. Observe that the compressed graph must satisfy certain properties we defined in subtask 2. Once again, the degree of each node must not be greater than which means that the graph is a series of chains or rings. The only case that is different from subtask 2 is that it is possible to have a ring consisting of all letters but any smaller ring would be invalid. Taking this special case in mind, we can perform the same procedure and perform a depth first search on each component to assign letters.

Time complexity: