#include #include #include #include #include #include #include template using MinHeap = std::priority_queue, std::greater>; template std::map compress(std::vector& v) { std::sort(v.begin(), v.end()); v.erase(std::unique(v.begin(), v.end()), v.end()); std::map rev; for (int i = 0; i < (int)v.size(); ++i) rev[v[i]] = i; return rev; } template struct Edge { int src, dst; Cost cost; Edge(int src = -1, int dst = -1, Cost cost = 1) : src(src), dst(dst), cost(cost){}; bool operator<(const Edge& e) const { return this->cost < e.cost; } bool operator>(const Edge& e) const { return this->cost > e.cost; } }; template struct Graph { std::vector>> graph; Graph(int n = 0) : graph(n) {} void span(bool direct, int src, int dst, Cost cost = 1) { graph[src].emplace_back(src, dst, cost); if (!direct) graph[dst].emplace_back(dst, src, cost); } int size() const { return graph.size(); } void clear() { graph.clear(); } void resize(int n) { graph.resize(n); } std::vector>& operator[](int v) { return graph[v]; } std::vector> operator[](int v) const { return graph[v]; } }; template std::vector dijkstra(const Graph& graph, int s) { std::vector dist(graph.size(), -1); dist[s] = 0; MinHeap> que; que.emplace(0, s); while (!que.empty()) { int v; Cost d; std::tie(d, v) = que.top(); que.pop(); if (d > dist[v]) continue; for (const auto& e : graph[v]) { if (dist[e.dst] != -1 && dist[e.dst] <= dist[v] + e.cost) continue; dist[e.dst] = dist[v] + e.cost; que.emplace(dist[e.dst], e.dst); } } return dist; } using lint = long long; void solve() { int n, m, k, s, t; std::cin >> n >> m >> k >> s >> t; --s, --t; auto enc = [&](int x, int y) { return x + lint(y) * n; }; std::vector> es; std::vector> yss(n); yss[0].push_back(s); yss[n - 1].push_back(t); while (m--) { int x, y1, y2; std::cin >> x >> y1 >> y2; --x, --y1, --y2; yss[x].push_back(y1); yss[x + 1].push_back(y2); es.emplace_back(enc(x, y1), enc(x + 1, y2)); } std::vector vs; for (int x = 0; x < n; ++x) { auto& ys = yss[x]; compress(ys); for (auto y : ys) vs.push_back(enc(x, y)); } auto vrev = compress(vs); int nn = vs.size(); Graph graph(nn); for (auto [u, v] : es) graph.span(true, vrev[u], vrev[v], 0); for (int x = 0; x < n; ++x) { auto& ys = yss[x]; int l = ys.size(); for (int i = 0; i + 1 < l; ++i) { int u = vrev[enc(x, ys[i])], v = vrev[enc(x, ys[i + 1])]; graph.span(false, u, v, ys[i + 1] - ys[i]); } } auto ds = dijkstra(graph, vrev[enc(0, s)]); auto ans = ds[vrev[enc(n - 1, t)]]; std::cout << ans << "\n"; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }