This page is still under construction.

Parts of this page are still being built. What you see may change.

Almost Shortest Path

Time limit1sMemory limit256 MB

Summary
Remove every edge that lies on any shortest S to D path, then find the shortest remaining path from S to D, or report -1.
Level

Medium7 of 10

Topics
Shortest path, Graph, Dynamic programming
Solved
No attempts yet

Problem

Many cars come with a GPS navigation system that finds the shortest path between the start and the destination that the user enters. But if the traffic situation is ignored and everyone is guided along the shortest path, that path can become severely congested.

So you are building a navigation system, used only by yourself, that never guides along a shortest path and always guides along an almost shortest path instead.

An almost shortest path is the shortest path, from the start to the destination, that is made up only of roads which do not belong to any shortest path. In other words, remove every road that is used by one or more shortest paths, then find the shortest path using only the remaining roads.

There may be several almost shortest paths, and there may be none at all. When none exists, its length is defined as −1-1.

Input

The input consists of several test cases.

The first line of each test case contains the number of places NN (2≤N≤5002 \le N \le 500) and the number of roads MM (1≤M≤1041 \le M \le 10^4). The places are numbered from 00 to N−1N-1.

The second line contains the start SS and the destination DD. (S≠DS \ne D; 0≤S,D<N0 \le S, D < N)

Each of the next MM lines contains three integers UU, VV, PP, meaning there is a one-way road of length PP from UU to VV. (U≠VU \ne V; 0≤U,V<N0 \le U, V < N; 1≤P≤1031 \le P \le 10^3)

There is at most one road from UU to VV, and the road U→VU \to V is different from the road V→UV \to U.

The last line of the input contains two zeros, and this line must not be processed.

Output

For each test case, print the length of the almost shortest path on its own line. If no almost shortest path exists, print −1-1.

Examples1

  1. Example 1

    Input
    7 9
    0 6
    0 1 1
    0 2 1
    0 3 2
    0 4 3
    1 5 2
    2 6 4
    3 6 2
    4 6 4
    5 6 1
    4 6
    0 2
    0 1 1
    1 2 1
    1 3 1
    3 2 1
    2 0 3
    3 0 2
    6 8
    0 1
    0 1 1
    0 2 2
    0 3 3
    2 5 3
    3 4 2
    4 1 1
    5 1 1
    3 0 1
    0 0
    
    Expected output
    5
    -1
    6