#include "bits/stdc++.h" using namespace std; #define int long long #define FOR(i, a, b) for(int i=(a);i<(b);i++) #define RFOR(i, a, b) for(int i=(b-1);i>=(a);i--) #define REP(i, n) for(int i=0; i<(n); i++) #define RREP(i, n) for(int i=(n-1); i>=0; i--) #define ALL(a) (a).begin(),(a).end() #define UNIQUE_SORT(l) sort(ALL(l)); l.erase(unique(ALL(l)), l.end()); #define CONTAIN(a, b) find(ALL(a), (b)) != (a).end() #define array2(type, x, y) array, x> #define vector2(type) vector > #define out(...) printf(__VA_ARGS__) int dxy[] = {0, 1, 0, -1, 0}; void solve(); signed main() { #if DEBUG std::ifstream in("input.txt"); std::cin.rdbuf(in.rdbuf()); #endif cin.tie(0); ios::sync_with_stdio(false); solve(); return 0; } /*================================*/ #if DEBUG #define SIZE 100 #else #define SIZE 223450 #endif int N,M,K,S,T; map MAP[SIZE]; struct Edge { int src, to, w; Edge(int u, int v, int w): src(u), to(v), w(w) {}; }; vector< vector > E(SIZE); void add_edge(int u, int v, int w) { E[u].push_back(*new Edge(u,v,w)); E[v].push_back(*new Edge(v,u,w)); } int C[SIZE]; void solve() { cin>>N>>M>>K>>S>>T; int a,b,c; int id = 1; REP(i,M) { cin>>a>>b>>c; a--; MAP[a][b] = id++; MAP[a+1][c] = id++; E[MAP[a][b]].push_back(*new Edge(MAP[a][b],MAP[a+1][c],0)); } if (!MAP[0][S]) MAP[0][S] = id++; if (!MAP[N-1][T]) MAP[N-1][T] = id++; REP(i,N) { int prev = -1; for (auto p:MAP[i]) { int floor = p.first; int id = p.second; if (prev>-1) { int diff = floor - prev; int previd = MAP[i][prev]; add_edge(previd, id, diff); } prev = floor; } } REP(i,SIZE) C[i]=LONG_LONG_MAX; queue que; que.push(MAP[0][S]); C[MAP[0][S]] = 0; while(!que.empty()) { int id = que.front(); que.pop(); for (auto e:E[id]) { int cost = C[id] + e.w; if (cost < C[e.to]) { C[e.to] = cost; que.push(e.to); } } } int ans = C[MAP[N-1][T]]; cout << (ans==LONG_LONG_MAX ? -1 : ans) << endl; }