Lexicographically Minimum Walk
Time limit2sMemory limit1024 MB
Find the lexicographically smallest color sequence among all walks from S to T of length at most 10^100, reporting IMPOSSIBLE or TOO LONG when needed.
- Level
Hard8 of 10
- Topics
- Graph, Greedy, BFS, Implementation
- Solved
- No attempts yet
Problem
There is a directed graph with nodes and edges. Each node is numbered through , and each edge is numbered through . For each (), edge goes from vertex to vertex and has a unique color .
A walk is a sequence of edges where for each , (the tail of edge ) is the same as (the head of edge ). We say a walk starts at vertex and ends at vertex . The same edge can appear multiple times in a walk.
The color sequence of a walk is defined as .
Consider all color sequences of walks of length at most from vertex to vertex in . Write a program that finds the lexicographically minimum sequence among them.
Input
The first line of the input contains four space-separated integers , , , and (, , , , ).
Then lines follow: the ()-th of them contains three space-separated integers , , and (, , ); it describes a directed edge from vertex to vertex with color .
The graph has no multiple edges and no loops, and each edge has a unique color. Formally, for any , and .
Output
If there is no walk from vertex to vertex , print "IMPOSSIBLE". (without quotes)
Otherwise, let be the lexicographically minimum sequence among all color sequences of walks of length at most from vertex to vertex .
- If , print in the first line. There should be a space between each printed integer.
- If , print "
TOO LONG". (without quotes)
Notes
A sequence is lexicographically smaller than another sequence if and only if one of the following holds:
- There is a unique () where , , , and .
- and , , , . In other words, is a strict prefix of .