Bracket Path
Time limit0.2sMemory limit512 MB
Given a directed graph whose edges carry bracket symbols, find the length of a shortest path from s to t whose edge labels form a correct bracket expression, or -1 if none exists.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Dynamic programming, Shortest path
- Solved
- No attempts yet
Problem
A bracket symbol is one of the eight characters (, ), [, ], {, }, <, >. A string made only of bracket symbols is a correct bracket expression when both of the following hold:
- every left bracket has a matching right bracket of the same kind, and every right bracket is matched;
- no two pairs of matching brackets cross. Any two such pairs are either disjoint, or one pair lies entirely inside the other.
For example, ([])<> is a correct bracket expression, while <{>} is not, because the curly pair and the angle pair cross each other.
You are given a directed graph with vertices. Every edge carries one bracket symbol. A path is valid when the symbols on its edges, read in order, form a correct bracket expression. Find the length of a shortest valid path from vertex to vertex . The path may pass through the same vertex several times. The length of a path is the number of edges on it.
The empty path uses no edges, and the empty string is a correct bracket expression, so the answer is when equals .
Input
The first line contains four integers , , , (, , ): the number of vertices, the number of edges, the starting vertex, and the ending vertex.
Each of the next lines contains two integers , and a bracket symbol (), describing an edge from vertex to vertex labeled with . The graph may contain loops and multiple edges.
Output
Print one line with one integer, the length of the shortest valid path from to . If no such path exists, print . If a path exists, its length does not exceed .