Lexicopolis
Time limit2sMemory limit1024 MB
Find the lexicographically smallest walk of exactly k edges from s to t, comparing edge magic numbers, and output its polynomial value modulo 1e9+7.
- Level
Hard8 of 10
- Topics
- Graph, Dynamic programming, String
- Solved
- No attempts yet
Problem
Lexicopolis is an ancient city known for its legends and treasures. The city is known for its tangled network of one-way roads. There are intersections and one-way roads. Road lets people travel only from intersection to intersection , and it carries a magic number .
A path of length from to is a sequence of roads that can be traveled in order from to . When two paths are compared, look at the first position where their magic numbers differ. The path with the smaller number at that position is lexicographically smaller. Compare the magic numbers, not the road indices.
A rumor says that a tourist who finds the lexicographically smallest path of length from to receives a gift from the government. Write a program that finds this path.
Input
The first line contains six integers , , , , , and . Here is the number of intersections, is the number of roads, is the starting intersection, is the destination intersection, is the base used in the final answer, and is the path length. Each of the next lines contains three integers , , and . This means road goes from to and has magic number .
Output
If no path of length from to exists, print -1. Otherwise, take the lexicographically smallest path and print the value of modulo .
Constraints
- , and
- Each ordered pair appears at most once.