Hamiltonian Circuit
Time limit1.5sMemory limit512 MB
Insert vertices one by one into a directed cycle in a tournament by the two given rules, and print -1 when no rule applies.
- Level
Medium7 of 10
- Topics
- Graph, Simulation
- Solved
- No attempts yet
Problem
A directed graph has vertices and edges. The vertices are numbered 0 to . For two distinct vertices and , exactly one of the edge from to and the edge from to is present, so is a complete graph once you ignore the directions.
is the adjacency matrix of . is + when the edge from to is present and - when it is not. is always ..
A Hamiltonian circuit of is a cycle of length that passes through every vertex of once. Given , decide whether a Hamiltonian circuit exists, and print one if it does.
Input
The first line has the number of vertices . Each of the next lines has one row of the adjacency matrix . The -th character of the -th of those lines is .
Output
If has no Hamiltonian circuit, print -1.
Otherwise print the vertices of a Hamiltonian circuit in the order they are passed, separated by one space. A graph can have several Hamiltonian circuits, so print exactly the one that the procedure below builds.
Keep a sequence of distinct vertices. The sequence stands for the cycle , and every neighbouring pair, including the pair , is an edge of . Start from the sequence that holds vertex 0 alone and repeat the following until the sequence holds all vertices. A vertex outside the sequence is called free.
- If a free vertex has both an edge from a sequence vertex to and an edge from to a sequence vertex, take the smallest such . Find the smallest index with equal to
+and equal to+, then put directly after . Such an index always exists. - Otherwise, collect the pairs of free vertices where every sequence vertex has an edge to , has an edge to every sequence vertex, and the edge from to is present. Take the smallest such pair in lexicographic order and append and then to the end of the sequence.
When has a Hamiltonian circuit, one of the two rules applies at every turn, and vertex 0 stays in front of the sequence, so the printed circuit starts at vertex 0.