The Walk of Bytie-boy
Time limit1sMemory limit128 MB
For each consecutive pair of stops in a city of one-way lettered streets, find the shortest walk whose letter sequence is a palindrome, tie-broken by lexicographically smallest string.
- Level
Hard8 of 10
- Topics
- BFS, Graph, Dynamic programming, Shortest path
- Solved
- No attempts yet
Problem
Bytie-boy is one of the youngest residents of Byteburg. He has only just learned to read and write, but he is old enough to walk to school on his own. Every morning he leaves home and calls on each of his friends in turn; the whole group sets off to school together only once everyone has joined.
One day the teacher asked Bytie to prepare a list of the streets he walks on his way to school and to read it aloud in the next class. To keep the list short, Bytie decided to write down only the first letter of the name of each street he uses. All streets in Byteburg are one-way, and each one connects two different crossings.
Bytie pauses only at the crossings where he picks up a friend, so each part of his walk (between two consecutive stops) reads as a single word. Reading is still hard for him, and he sometimes reads a word right to left instead of left to right, so he might read milk as either milk or klim. To spare him mistakes, his parents want a route in which every such word is a palindrome: it reads the same left to right and right to left. They also want each word to be as short as possible.
You are given the city and the ordered list of crossings where Bytie stops. For each consecutive pair of stops, find the shortest walk along the one-way streets whose sequence of first letters forms a palindrome.
Input
The first line contains two integers and (, ): the number of crossings in Byteburg and the number of one-way streets.
Each of the next lines contains two integers and a letter, (, , ), describing a one-way street that leads from crossing to crossing and whose name starts with the lowercase English letter . For any ordered pair of crossings there is at most one street, so there is at most one street from to and at most one from to .
The next line contains one integer (): the number of crossings on Bytie's route.
The last line contains integers (): the crossings in the order Bytie visits them, where is his home and is the school. Every two consecutive values differ, but values that are not adjacent may be equal.
Output
Print lines. On the -th line describe the shortest palindromic walk from crossing to crossing along the one-way streets: print its length (the number of streets used) and then, separated by a single space, the string of first letters read along that walk. A walk is palindromic when reads the same left to right and right to left; a walk of a single street counts as palindromic. If several shortest palindromic walks exist, print the one whose letter string is lexicographically smallest. If no palindromic walk from to exists, print -1 on that line instead.
Hint
