King of the Waves
Time limit2sMemory limit512 MB
Decide whether Henk (participant 0) can be made tournament king, and if so print the specified BFS-tree order reversed.
Problem
You run a king of the hill tournament with participants, the Buenos Aires Paddleboarding Competition (BAPC). One participant starts as king and the others challenge the king one at a time. The winner of a match becomes the new king. Every participant except the starting one challenges exactly once, and a paddleboarding match never ends in a draw. Whoever is king after the last match wins the tournament.
You are the organiser, so you pick who starts as king and the order of the challenges. Someone offers you a large sum of money if participant , Henk, wins the tournament. You happen to know, for any two participants and , which of them would win their match. So you decide to rig the game. Decide whether a schedule that makes Henk win exists, and if it does, print the schedule defined in the output section.
Input
The first line contains an integer (), the number of participants. The participants are numbered to , and Henk is participant .
Each of the next lines contains exactly characters. The -th character of the -th line describes the match between participant and participant ():
1if participant beats participant ,0if participant loses to participant ,Xif .
Output
If no schedule makes Henk win, print impossible.
Otherwise print the single schedule defined by the rule below.
Build a tree rooted at participant with a breadth first search. Mark participant as visited and put it in a queue. While the queue is not empty, take the participant at the front of the queue and look at in increasing order. Whenever is not visited yet and beats , mark as visited, record as the parent of , and push to the back of the queue. A schedule that makes Henk win exists if and only if this search visits every participant.
Traverse that tree in preorder, visiting a participant before its children and visiting the children of a participant in increasing order of index. Print the traversal reversed on one line, with the numbers separated by single spaces. The participant printed first starts as king, and the others challenge the king in the printed order.
Whenever some schedule makes Henk win, this schedule makes him win too. Other winning schedules can exist, and only this one is accepted.