#include "iostream" #include "climits" #include "list" #include "queue" #include "stack" #include "set" #include "functional" #include "algorithm" #include "string" #include "map" #include "unordered_map" #include "iomanip" #include "cmath" using namespace std; const long long int MOD = 1000000007; long long int N, M, K, H, W, L, R; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> N >> M >> K >> L >> R; vector>edge; vector>m(N + 1); mapdis; for (int i = 0; i < M; i++) { long long int a, b, c; cin >> a >> b >> c; m[a][b]++; m[a + 1][c]++; edge.push_back({ a*MOD + b,(a + 1)*MOD + c }); edge.push_back({ (a + 1)*MOD + c,a*MOD + b }); } sort(edge.begin(), edge.end()); m[1][L]++; m[N][R]++; for (int i = 1; i <= N; i++) { for (auto j : m[i]) { dis[i*MOD + j.first] = LLONG_MAX; } } dis[MOD + L] = 0; priority_queue, vector>, greater>>PQ; PQ.push({ 0,MOD + L }); while (!PQ.empty()) { auto box = PQ.top(); PQ.pop(); int cw = box.second / MOD; int ch = box.second %MOD; long long int cc = box.first; if (dis[cw*MOD + ch] > cc) { continue; } auto it = m[cw].find(ch); if (it != m[cw].begin()) { it--; int nh = (*it).first; if (dis[cw*MOD + nh] > cc + abs(nh - ch)) { dis[cw*MOD + nh] = cc + abs(nh - ch); PQ.push({ dis[cw*MOD + nh],cw*MOD + nh }); } it++; } it++; if (it != m[cw].end()) { int nh = (*it).first; if (dis[cw*MOD + nh] > cc + abs(nh - ch)) { dis[cw*MOD + nh] = cc + abs(nh - ch); PQ.push({ dis[cw*MOD + nh],cw*MOD + nh }); } } auto itb = lower_bound(edge.begin(), edge.end(), make_pair(cw*MOD + ch, (long long int)0)); auto ite = lower_bound(edge.begin(), edge.end(), make_pair(cw*MOD + ch + 1, (long long int)0)); for (; itb != ite; ++itb) { int n = (*itb).second; if (dis[n] > cc) { dis[n] = cc; PQ.push({ cc,n }); } } } if (dis[N*MOD + R] == LLONG_MAX) { cout << -1 << endl; return 0; } cout << dis[N*MOD + R] << endl; return 0; }