Bracket Path

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.

Hard8GraphBFSDynamic programmingShortest pathNo attempts yetTime limit0.2sMemory limit512 MB

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 nn 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 ss to vertex tt. 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 00 when ss equals tt.

Input

The first line contains four integers nn, mm, ss, tt (1n2001 \leq n \leq 200, 0m20000 \leq m \leq 2000, 1s,tn1 \leq s, t \leq n): the number of vertices, the number of edges, the starting vertex, and the ending vertex.

Each of the next mm lines contains two integers xx, yy and a bracket symbol bb (1x,yn1 \leq x, y \leq n), describing an edge from vertex xx to vertex yy labeled with bb. The graph may contain loops and multiple edges.

Output

Print one line with one integer, the length of the shortest valid path from ss to tt. If no such path exists, print 1-1. If a path exists, its length does not exceed 101810^{18}.