Railroad and Hamilton

Problem #457  

Tags: graphs implementation c-1

Who solved this?

No translations... yet
example of railroad graph with switches

Railroad graph is similar to general graph in that it also has "edges" - tracks wich connect "nodes". However nodes themselves are unusual - they are typical switches. Let's look closer: switch has 3 "ends" to which tracks could be connected, so it is almost like the node with up to 3 edges. However not all travel directions between these ends are possible!

Let's enumerate switch "ends" with digits 0, 1 and 2, and agree that switch allows to divert the train coming from 0 either to 1 or to 2. Of course moving in opposite direction is also possible - trains coming from 1 or from 2 will leave through 0 end. However there is no way to go from 1 to 2 or vice versa.

In special cases, generally when doing some maneurs for rearranging train cars, especially on auxiliary tracks, it is allowed to move past the switch, say from 1 via 0 and then "switch" it and go carefully backwards from 0 to 2 - but this way we have the engine in the tail of the train so such manipulations are generally prohibited on main tracks.

Let's have a look at the picture above. There switches are shown in blue and tracks connecting them are in black. Switch A has its ends marked for clarity - so you see, it is possible to travel from C to D via A or from B to C via A, but to travel from B to D we'll need a route B-A-C-D or B-G-F-E-D depending on which side train was oriented.

In this problem the engineer named Hamilton wants to travel over railroad network visiting every switch once (suppose there are small villages around the switches and he collects mail in non-stop manner). It is called "Hamiltonian" of course.

If the goal could not be achieved on a given network, this case should be reported to officials.

Input data:

For example, switch description A C2 B0 D2 means that switch A has:

Some switch end could be left unconnected, which is marked by dash symbol.

Answer: should contain description of the route for each network, if it exists, or the word report otherwise. Combine all answers with spaces as usually. Route description should contain sequence of switch ends by which train leaves each of the switches it passes. No need to add switch ends by which train approaches the switch - and also there is no need to mention the last switch - thus the sequence will contain 2 * (N-1) characters.

Example:

input data:
2
5
A: D2 E1 E0
B: B2 C0 B0
C: B1 - E2
D: D1 D0 A0
E: A2 A1 C2
6
A: F1 C0 B1
B: E1 A2 C1
C: A1 B2 D1
D: F0 C2 E0
E: D2 B0 F2
F: D0 A0 E2

answer:
B1C2E0A0 F1A1C1B0E0
You need to login to get test data and submit solution.