#include "bits/stdc++.h" using namespace std; #define DEBUG(x) cout<<#x<<": "< #define vl vector #define vii vector< vector > #define vll vector< vector > #define vs vector #define pii pair #define pll pair #define pis pair #define psi pair const int inf = 1000000001; const ll INF = 1e18 * 2; #define MOD 1000000007 #define mod 1000000009 #define pi 3.14159265358979323846 #define Sp(p) cout< > adj(N,vector()); vl d(N,INF); map mp; int cnt = 1; void dijkstra(){ priority_queue, greater > pq; int i; vi color(cnt - 1,WHITE); d[1]=0; pq.push(make_pair(0,1)); color[1]=GRAY; while(!pq.empty()){ pll f=pq.top(); pq.pop(); ll u=f.second; color[u]=BLACK; if(d[u]d[u]+adj[u][i].first){ d[v]=d[u]+adj[u][i].first; pq.push(make_pair(d[v],v)); color[v]=GRAY; } } } } int main() { int n, m, k, s, t, i; cin >> n >> m >> k >> s >> t; s--; t--; vector > floor(n); floor[0].insert(s); floor[n - 1].insert(t); mp[pll(0, s)] = cnt++; mp[pll(n - 1, t)] = cnt++; for (i = 0; i < m; i++) { ll a, b, c; cin >> a >> b >> c; a--; b--; c--; if (mp[pll(a, b)] == 0) { mp[pll(a, b)] = cnt++; floor[a].insert(b); } if (mp[pll(a + 1, c)] == 0) { mp[pll(a + 1, c)] = cnt++; floor[a + 1].insert(c); } adj[mp[pll(a, b)]].push_back(pll(0, mp[pll(a + 1, c)])); adj[mp[pll(a + 1, c)]].push_back(pll(0, mp[pll(a, b)])); } for (i = 0; i < n; i++) { auto pre = floor[i].begin(); auto itr = floor[i].begin(); itr++; for (; itr != floor[i].end(); itr++, pre++) { ll a = *pre, b = *itr; //cout << i << " " << a << " " << b << endl; ll u = mp[pll(i, a)], v = mp[pll(i, b)]; adj[u].push_back(pll(abs(b - a), v)); adj[v].push_back(pll(abs(a - b), u)); } } dijkstra(); if (d[mp[pll(n - 1, t)]] == INF) { cout << -1 << endl; } else { cout << d[mp[pll(n - 1, t)]] << endl; } } /* 2 1 5 1 5 1 3 4 2 2 10 10 1 1 9 5 1 6 1 2 0 5 1 5 */