Similar Cities
Time limit2sMemory limit128 MB
Find the shortest digit string that reaches a house from the town hall in exactly one of two given directed labeled graphs.
- Level
Medium6 of 10
- Topics
- BFS, Graph, Shortest path
- Solved
- No attempts yet
Problem
In SBP (the Super Rich Country) there are a great many cities. Every city contains houses, shops, and exactly one town hall. SBP is a very orderly country, so every city has a degree. A degree of means that exactly one-way roads leave every building, numbered through .
Paths that start at the town hall are especially important. Such a path is described by the sequence of road numbers taken along the way. For example, the path described by the sequence is walked like this:
- Start at the town hall. Take the road numbered , arriving at building .
- Take road number from to building .
- Take road number from to building .
- The path ends at building , which may be a house, a shop, or the town hall.
You are given the road layouts of two cities that share the same degree . Find the shortest sequence that, in one of the two cities, describes a path from the town hall to a house, while in the other city it describes a path from the town hall to a building that is not a house (a shop or the town hall). In other words, find the shortest sequence for which the two cities disagree on whether the walk ends at a house.
Each road number is a single digit from to (note ), so a sequence is written as its road numbers joined together with no separators.
Input
The first line contains the number of test cases (). Each test case is given as follows.
The first line of a test case has five integers , , , , (, , , ): the number of buildings in the first city, the number of houses in the first city, the number of buildings in the second city, the number of houses in the second city, and the degree shared by both cities.
In each city the town hall is building , the houses are buildings through , and the shops are buildings through .
The next lines describe the first city: line (counting buildings from ) contains integers in the range to , the destinations of roads leaving building . The following lines describe the second city in the same way. Several roads may connect the same pair of buildings, and a road may start and end at the same building.
Output
Print lines; the -th holds the answer for the -th test case. If no valid sequence exists, print a single . Otherwise print the length of the shortest valid sequence, then a single space, then the sequence itself. If several shortest sequences exist, print the lexicographically smallest one (the one that would come first in a dictionary).