import java.util.*; public class Dijkstra { static int distance(ArrayList[] adj, ArrayList[] cost, int s, int t) { if (s == t) return 0; int[] dist = new int[adj.length]; //int[] prev = new int[adj.length]; boolean[] visited = new boolean[adj.length]; for (int i = 0; i < dist.length; i++) { dist[i] = Integer.MAX_VALUE; //prev[i] = -1; } dist[s] = 0; PriorityQueue vertexQ; vertexQ = new PriorityQueue(Comparator.comparingInt(a -> dist[a])); vertexQ.add(s); while (!vertexQ.isEmpty()) { int u = vertexQ.remove(); if (visited[u]) { continue; } visited[u] = true; if (adj[u].size() > 0) { for (int i = 0; i < adj[u].size(); i++) { if (dist[adj[u].get(i)] > dist[u] + cost[u].get(i)) { dist[adj[u].get(i)] = dist[u] + cost[u].get(i); //prev[adj[u].get(i)] = u; vertexQ.add(adj[u].get(i)); } } } } if (dist[t] == Integer.MAX_VALUE) return -1; return dist[t]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); ArrayList[] adj = (ArrayList[]) new ArrayList[n]; ArrayList[] cost = (ArrayList[]) new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList(); cost[i] = new ArrayList(); } for (int i = 0; i < m; i++) { int x, y, w; x = scanner.nextInt(); y = scanner.nextInt(); w = scanner.nextInt(); adj[x - 1].add(y - 1); cost[x - 1].add(w); } int x = scanner.nextInt() - 1; int y = scanner.nextInt() - 1; System.out.println(distance(adj, cost, x, y)); } }