The Bike Trip
Time limit3sMemory limit128 MB
Starting from place 1, follow staged runs of typed directed roads and list every possible end place.
Problem
The weather is mild and dry, perfect for a bike trip! Hektor grabbed a map of the nearby towns and the roads connecting them (bridges, viaducts, dirt tracks, and so on) and started planning a route, but in an unusual way.
Instead of writing down which places he would visit, Hektor wrote down, in order, the types of road he would ride along. Every road has a type number, and his plan is a list of stages, where each stage means "ride roads of type in a row".
Because only the road types are fixed, the actual sequence of visited places is not unique, so many different routes may match the plan. Hektor wants to know where his trip could end. The trip always starts at place . Following the plan exactly, find every place where the trip could end.
Input
The first line contains the number of test cases (). The descriptions of the test cases follow.
Each test case begins with a line containing two integers and (, ): the number of places and the number of roads on the map. Each of the next lines contains three integers , , and (, ), meaning that from place you can travel to place along a road of type . No two roads share the same start place and end place at the same time.
After the map, a line contains one integer (). Each of the next lines contains two integers and (, ), meaning that in this stage Hektor rides roads of type .
Output
For each test case, print two lines. The first line contains a single integer: the number of places where Hektor's trip could end. The second line lists those places in increasing order.
Hint
On the first sample map, the plan leaves no choice: Hektor rides through the places in order, so the trip must end at place .
On the same map, a plan that rides four roads of type from the start allows two routes, and , so the trip can end at place or place .