#include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define mt make_tuple #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)< pii; typedef vector vi; typedef vector vll; typedef long long Weight; struct Edge { int from, to; Weight wei; Edge(int from_, int to_, Weight wei_) :from(from_), to(to_), wei(wei_) {} }; typedef vector Edges; const Weight INFW = numeric_limits::max(); struct Graph : public vector { Graph() { } Graph(int V) : vector(V) { } /* 有向辺を追加する */ void addEdge(int from, int to, Weight wei = 1) { (*this)[from].push_back(Edge(from, to, wei)); } /* 無向辺を追加する */ void addUEdge(int u, int v, Weight wei = 1) { (*this)[u].push_back(Edge(u, v, wei)); (*this)[v].push_back(Edge(v, u, wei)); } }; vector dijkstra(const Graph &G, int src) { typedef pair pwi; priority_queue, greater> pq; pq.push(mp(0, src)); int V = (int)G.size(); vector res(V, -1); while (pq.size()) { auto p = pq.top(); pq.pop(); Weight d = p.first; int v = p.second; if (res[v] > -1)continue; res[v] = d; for (const auto &edge : G[v]) { int to = edge.to; Weight wei = edge.wei; pq.push(make_pair(d + wei, to)); } } return res; } int N, M, K, S, T; int L = 0; map id[200005]; int f(int n, int k) { if (!id[n].count(k)) { id[n][k] = L++; } assert(id[n].count(k)); return id[n][k]; }; int main(){ ios::sync_with_stdio(false); cin.tie(0); vector E; cin >> N >> M >> K >> S >> T; rep(i, M) { int a, b, c; cin >> a >> b >> c; E.emplace_back(f(a, b), f(a + 1, c)); } f(1, S); f(N, T); Graph G(L); each(e, E) { G.addEdge(e.first, e.second, 0); } for (int i = 1; i <= N; ++i) { auto end = id[i].end(); for (auto a = id[i].begin(); a != end; ++a) { auto b = a; if (++b == end)break; int d = b->first - a->first; G.addUEdge(a->second, b->second, d); } } auto d = dijkstra(G, f(1, S)); ll ans = d[f(N, T)]; if (ans == LLONG_MAX)ans = -1; cout << ans << endl; }