#include using namespace std; struct Edge { int ffloor, to, tfloor; Edge() {} Edge(int ffloor, int to, int tfloor) : ffloor(ffloor), to(to), tfloor(tfloor) {} }; struct edge { int to; long long cost; edge() {} edge(int to, long long cost) : to(to), cost(cost) {} }; int N, M, K, S, T, a, b, c, cnt; set st[200001]; // 各棟で使われている階 vector > E; // 与えられる辺 vector > g; // 頑張って作ったグラフ map, int> mp; // {棟の番号, 階数} -> idx vector d; void dijkstra(int s) { priority_queue, vector >, greater > > que; d.resize(cnt, int(1e9)); d[s] = 0; que.push({0, s}); while(!que.empty()) { pair p = que.top(); que.pop(); int v = p.second, size_; if (d[v] < p.first) continue; size_ = g[v].size(); //cerr << v << endl; assert(0 <= v && v < cnt); for (int i = 0; i < size_; ++i) { edge e = g[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.push({d[e.to], e.to}); } } } } int main() { cin.tie(0), cout.tie(0); ios::sync_with_stdio(false); cin >> N >> M >> K >> S >> T, K--, S--, T--; E.resize(N); for (int i = 0; i < M; ++i) { cin >> a >> b >> c; a--, b--, c--; st[a].insert(b); st[a + 1].insert(c); E[a].push_back({b, a + 1, c}); } st[0].insert(S); st[N - 1].insert(T); int start = -1, goal; pair prev; for (int i = 0; i < N; ++i) { prev = {-1, -1}; for (auto v : st[i]) { mp[{i, v}] = cnt++; if (prev.first != -1) { E[i].push_back({prev.second, i, v}); } prev = {i, v}; } } g.resize(cnt); for (int i = 0; i < N; ++i) { for (auto e : E[i]) { g[mp[{i, e.ffloor}]].push_back({mp[{e.to, e.tfloor}], (i == e.to ? abs(e.ffloor - e.tfloor) : 0)}); g[mp[{e.to, e.tfloor}]].push_back({mp[{i, e.ffloor}], (i == e.to ? abs(e.ffloor - e.tfloor) : 0)}); } } start = mp[{0, S}]; goal = mp[{N - 1, T}]; //cerr << "start is " << start << endl; mp.clear(); E.clear(); dijkstra(start); //cerr << "end\n"; cout << (d[goal] == int(1e9) ? -1 : d[goal]) << endl; /* for (int i = 0; i < cnt; ++i) { for (auto v : g[i]) { cerr << i << " " << v.to << " " << v.cost << endl; } } //*/ return 0; }