#include #include #include #include #include #include #define int long long using namespace std; typedef pair P; int INF = 1e+15; int n, m, k, s, t; int a[200000], b[200000], c[200000]; vector

points; vector heights[200001]; vector edgeTo[400002]; vector edgeCost[400002]; int dijkstra(int start, int goal) { static int minCost[400002]; static priority_queue, greater

> que; int i; for (i = 0; i < points.size(); i++) minCost[i] = INF; que.push(P(0, start)); while (!que.empty()) { P now = que.top(); que.pop(); int cst = now.first; int pos = now.second; if (minCost[pos] <= cst) continue; minCost[pos] = cst; if (pos == goal) break; for (i = 0; i < edgeTo[pos].size(); i++) { que.push(P(edgeCost[pos][i] + cst, edgeTo[pos][i])); } } return minCost[goal]; } signed main() { int i, j; cin >> n >> m >> k >> s >> t; for (i = 0; i < m; i++) { cin >> a[i] >> b[i] >> c[i]; points.push_back(P(a[i], b[i])); points.push_back(P(a[i] + 1, c[i])); heights[a[i]].push_back(b[i]); heights[a[i] + 1].push_back(c[i]); } points.push_back(P(1, s)); points.push_back(P(n, t)); sort(points.begin(), points.end()); points.erase(unique(points.begin(), points.end()), points.end()); heights[1].push_back(s); heights[n].push_back(t); for (i = 1; i <= n; i++) sort(heights[i].begin(), heights[i].end()); for (i = 0; i < m; i++) { int from = lower_bound(points.begin(), points.end(), P(a[i], b[i])) - points.begin(); int to = lower_bound(points.begin(), points.end(), P(a[i] + 1, c[i])) - points.begin(); edgeTo[from].push_back(to); edgeCost[from].push_back(0); } for (i = 1; i <= n; i++) { for (j = 0; j + 1 < heights[i].size(); j++) { int from = lower_bound(points.begin(), points.end(), P(i, heights[i][j])) - points.begin(); int to = lower_bound(points.begin(), points.end(), P(i, heights[i][j + 1])) - points.begin(); edgeTo[from].push_back(to); edgeTo[to].push_back(from); edgeCost[from].push_back(heights[i][j + 1] - heights[i][j]); edgeCost[to].push_back(heights[i][j + 1] - heights[i][j]); } } int start = lower_bound(points.begin(), points.end(), P(1, s)) - points.begin(); int goal = lower_bound(points.begin(), points.end(), P(n, t)) - points.begin(); int minCost = dijkstra(start, goal); if (minCost >= INF) cout << -1 << endl; else cout << minCost << endl; return 0; }