Insert vertices one by one into a directed cycle in a tournament by the two given rules, and print -1 when no rule applies.
Medium7GraphSimulationNo attempts yetTime limit1.5sMemory limit512 MBA directed graph G has N vertices and N(N−1)/2 edges. The vertices are numbered 0 to N−1. For two distinct vertices i and j, exactly one of the edge from i to j and the edge from j to i is present, so G is a complete graph once you ignore the directions.
X is the adjacency matrix of G. Xi,j is + when the edge from i to j is present and - when it is not. Xi,i is always ..
A Hamiltonian circuit of G is a cycle of length N that passes through every vertex of G once. Given G, decide whether a Hamiltonian circuit exists, and print one if it does.
The first line has the number of vertices N. Each of the next N lines has one row of the adjacency matrix X. The j-th character of the i-th of those lines is Xi,j.
If G has no Hamiltonian circuit, print -1.
Otherwise print the N 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 c0,c1,…,ck−1 of distinct vertices. The sequence stands for the cycle c0→c1→⋯→ck−1→c0, and every neighbouring pair, including the pair (ck−1,c0), is an edge of G. Start from the sequence that holds vertex 0 alone and repeat the following until the sequence holds all N vertices. A vertex outside the sequence is called free.
+ and Xv,c(i+1)modk equal to +, then put v directly after ci. Such an index i always exists.When G 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.