#include <iostream> #include <queue> #include <vector> #define pll pair<int,int> #define inf 100000009 using namespace std; int n,m,st,en; int a,b,w; vector<int> v[510]; priority_queue<pll,vector<pll>,greater<pll>> pq; int dist[510]; vector<int> route[510]; int we[510][510]; bool check[510]; void di(int x){ pq.push({0,x}); dist[x] = 0; while(!pq.empty()){ int cost = pq.top().first; int start = pq.top().second; pq.pop(); cout << "start : " << start << ", cost : " << cost << '\n'; for(int i=0; i<v[start].size(); i++){ int cc = we[start][v[start][i]]; if(cc==-1){ continue; } if(dist[v[start][i]] >= cost+cc){ if(dist[v[start][i]]>cost+cc){ route[v[start][i]].clear(); } dist[v[start][i]] = cost+cc; route[v[start][i]].push_back(start); pq.push({dist[v[start][i]],v[start][i]}); } } } } void del(int x){ vector<int> r; r.push_back(x); while(!r.empty()){ int s = r.back(); r.pop_back(); for(int i=0; i<route[s].size(); i++){ we[route[s][i]][s] = -1; if(check[route[s][i]]){ continue; } check[route[s][i]] = true; r.push_back(route[s][i]); } } } int main() { while(1){ cin >> n >> m; if(n==0 && m==0){ break; } cin >> st >> en; for(int i=0; i<510; i++){ v[i].clear(); route[i].clear(); check[i] = false; } for(int i=0; i<510; i++){ for(int j=0; j<510; j++){ we[i][j] = -1; } } for(int i=0; i<m; i++){ cin >> a >> b >> w; v[a].push_back(b); we[a][b] = w; } for(int i=0; i<510; i++){ dist[i] = inf; } di(st); del(en); for(int i=0; i<510; i++){ dist[i] = inf; } di(st); if(dist[en]==inf){ cout << -1 << "\n"; } else{ cout << dist[en] << "\n"; } } } /* 9 12 0 8 0 1 1 0 2 2 0 3 3 1 4 3 2 4 2 3 4 1 4 5 1 4 6 2 4 7 3 5 8 3 6 8 2 7 8 1 0 0 */
9 12 0 8 0 1 1 0 2 2 0 3 3 1 4 3 2 4 2 3 4 1 4 5 1 4 6 2 4 7 3 5 8 3 6 8 2 7 8 1 0 0
start : 0, cost : 0 start : 1, cost : 1 start : 2, cost : 2 start : 3, cost : 3 start : 4, cost : 4 start : 4, cost : 4 start : 4, cost : 4 start : 5, cost : 5 start : 5, cost : 5 start : 5, cost : 5 start : 6, cost : 6 start : 6, cost : 6 start : 6, cost : 6 start : 7, cost : 7 start : 7, cost : 7 start : 7, cost : 7 start : 8, cost : 8 start : 8, cost : 8 start : 8, cost : 8 start : 8, cost : 8 start : 8, cost : 8 start : 8, cost : 8 start : 8, cost : 8 start : 8, cost : 8 start : 8, cost : 8 start : 0, cost : 0 -1