#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; struct Edge { int a; int b; int c; Edge(int a = -1, int b = -1, int c = -1) { this->a = a; this->b = b; this->c = c; } bool operator<(const Edge &e) const { return b < e.b; } }; vector G[200010]; int main() { int N, M, K, S, T; cin >> N >> M >> K >> S >> T; for (int i = 0; i < M; ++i) { int a, b, c; cin >> a >> b >> c; G[a].push_back(Edge(a, b, c)); } set P[N + 1]; map> min_cost; map> visited; for (int i = 1; i <= N - 1; ++i) { sort(G[i].begin(), G[i].end()); } for (int i = 1; i < N; ++i) { if (G[i].empty()) { cout << -1 << endl; return 0; } if (i == 1) { for (Edge &e : G[i]) { min_cost[i][e.b] = abs(S - e.b); visited[i][e.b] = true; } } else { { int cur_pos = *P[i].begin(); ll cur_cost = min_cost[i][cur_pos]; for (Edge &e : G[i]) { ll new_cost = cur_cost + abs(e.b - cur_pos); if (not visited[i][e.b] || min_cost[i][e.b] > new_cost) { min_cost[i][e.b] = new_cost; cur_pos = e.b; cur_cost = new_cost; visited[i][e.b] = true; } } } { int cur_pos = *P[i].rbegin(); ll cur_cost = min_cost[i][cur_pos]; reverse(G[i].begin(), G[i].end()); for (Edge &e : G[i]) { ll new_cost = cur_cost + abs(e.b - cur_pos); if (not visited[i][e.b] || min_cost[i][e.b] > new_cost) { min_cost[i][e.b] = new_cost; cur_pos = e.b; cur_cost = new_cost; visited[i][e.b] = true; } } reverse(G[i].begin(), G[i].end()); } } for (Edge &e : G[i]) { // fprintf(stderr, "i: %d, b: %d, cost: %lld\n", i, e.b, min_cost[i][e.b]); if (not visited[i + 1][e.c] || min_cost[i + 1][e.c] > min_cost[i][e.b]) { min_cost[i + 1][e.c] = min_cost[i][e.b]; visited[i + 1][e.c] = true; } P[i + 1].insert(e.c); // fprintf(stderr, "%d: k: %d, cost: %lld\n", i + 1, e.c, min_cost[i + 1][e.c]); } } ll ans = LLONG_MAX; for (int k : P[N]) { ll cost = min_cost[N][k] + abs(k - T); ans = min(ans, cost); } cout << ans << endl; return 0; }