// 基本テンプレート #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++) #define repq(i,a,n) for(int (i)=(a); (i)<=(n); (i)++) #define repr(i,a,n) for(int (i)=(a); (i)>=(n); (i)--) #define int long long int template void chmax(T &a, T b) {a = max(a, b);} template void chmin(T &a, T b) {a = min(a, b);} template void chadd(T &a, T b) {a = a + b;} typedef pair pii; typedef long long ll; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; constexpr ll INF = 1001001001001001LL; constexpr ll MOD = 1000000007LL; vector edges[200010]; map< int, map > rec; signed main() { int N, M, K, S, T; cin >> N >> M >> K >> S >> T; rep(i,0,M) { int a, b, c; cin >> a >> b >> c; edges[a].push_back(make_pair(b, c)); } queue que; que.push(make_pair(1, S)); while(!que.empty()) { pii cur = que.front(); que.pop(); int idx = cur.first, flr = cur.second; for(auto e : edges[idx]) { int cur_flr = e.first, nxt_flr = e.second; int cost = abs(flr - cur_flr); // printf("cur_flr = %lld, nxt_flr = %lld, cost = %lld\n", cur_flr, nxt_flr, cost); if(!rec[idx+1].count(nxt_flr) || rec[idx+1][nxt_flr] > rec[idx][flr] + cost) { rec[idx+1][nxt_flr] = rec[idx][flr] + cost; que.push(make_pair(idx+1, nxt_flr)); } } } int ans = INF; for(auto x : rec[N]) { int flr = x.first, cost = x.second; // printf("flr = %lld, cost = %lld\n", flr, cost); chmin(ans, cost + abs(flr - T)); } if(ans == INF) cout << -1 << endl; else cout << ans << endl; return 0; }