Signs on the Road
Time limit2sMemory limit1024 MB
Find the lexicographically smallest digit string written while walking a graph to visit all towns, and the minimum toll for that string.
- Level
Hard9 of 10
- Topics
- Graph, Minimum spanning tree, Greedy, String
- Solved
- No attempts yet
Problem
Woohyeon became a traveling salesman and needs to visit every town numbered from to . He is currently in town . There are roads between the towns, and any two towns are connected by at most one road. Each road has two properties. First, each road has a sign with a digit from to . Second, each road has a toll, but the toll is paid only the first time the road is crossed. Crossing the same road again costs nothing.
Whenever Woohyeon crosses a road, he writes the digit on its sign on his phone. He can place the cursor anywhere before typing, so after writing "321" and crossing a road with a 4 sign, he can produce "3421" or "3214". However, he does not write the digit of a road he has already crossed.
Woohyeon never lacks the money for a toll, but he does not want to pay more than necessary. Still, he wants the number on his phone to be as small as possible, even if that costs a little more. Find the smallest number he can write on his phone while visiting all towns, and the minimum toll needed to write that number.
Input
The first line contains and , separated by a space. (, )
Each of the next lines contains , separated by spaces. This means towns and are connected by a road with sign , and its toll is won. (, , , )
Output
If it is impossible to visit all towns, print -1 on the first line.
If it is possible, print on the first line the smallest number that can be written on the phone while visiting all towns, and the minimum toll needed to write that number, separated by a space.