#include #define VARNAME(x) #x #define show(x) cerr << #x << " = " << x << endl using namespace std; using ll = long long; using ld = long double; template ostream& operator<<(ostream& os, const vector& v) { os << "sz:" << v.size() << "\n["; for (const auto& p : v) { os << p << ","; } os << "]\n"; return os; } template ostream& operator<<(ostream& os, const pair& p) { os << "(" << p.first << "," << p.second << ")"; return os; } constexpr ll MOD = (ll)1e9 + 7LL; constexpr ld PI = static_cast(3.1415926535898); template constexpr T INF = numeric_limits::max() / 10; struct CostGraph { using T = ll; CostGraph(const ll v) : V{v} { edge.resize(v); rev_edge.resize(v); } struct Edge { Edge(const ll from, const ll to, const T cost) : from{from}, to{to}, cost{cost} {} const ll from; const ll to; const T cost; bool operator<(const Edge& e) const { return cost != e.cost ? cost < e.cost : to < e.to; } }; void addEdge(const ll from, const ll to, const T cost = 1) { edge[from].push_back(Edge{from, to, cost}); rev_edge[to].push_back(Edge(to, from, cost)); } vector> edge; vector> rev_edge; const ll V; }; void Dijkstra(const CostGraph& g, const ll s, vector& d) { using T = CostGraph::T; assert(s < g.V); assert(d.size() == g.V); using P = pair; priority_queue, greater

> q; for (ll i = 0; i < g.V; i++) { d[i] = INF; } d[s] = 0; q.push(make_pair(0, s)); while (not q.empty()) { const P& p = q.top(); const T cost = p.first; const ll v = p.second; q.pop(); if (d[v] < cost) { continue; } for (const auto& e : g.edge[v]) { if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; q.push(make_pair(d[e.to], e.to)); } } } } int main() { cin.tie(0); ios::sync_with_stdio(false); ll N, M, K, S, T; cin >> N >> M >> K >> S >> T; S--, T--; vector num(N); vector> bridge(M); vector> pos(N); for (ll i = 0; i < M; i++) { ll a, b, c; cin >> a >> b >> c; a--, b--, c--; pos[a].push_back(b); num[a]++; pos[a + 1].push_back(c); num[a + 1]++; bridge[i] = make_tuple(a, b, c); } pos[0].push_back(S); num[0]++; pos[N - 1].push_back(T); num[N - 1]++; vector> mps(N); for (ll i = 0; i < N; i++) { num[i] += (i == 0 ? 0 : num[i - 1]); sort(pos[i].begin(), pos[i].end()); for (ll j = 0; j < pos[i].size(); j++) { mps[i][pos[i][j]] = j; } } CostGraph g(num[N - 1]); for (ll i = 0; i < N; i++) { for (ll j = 0; j < (int)pos[i].size() - 1; j++) { g.addEdge(j + (i == 0 ? 0 : num[i - 1]), j + 1 + (i == 0 ? 0 : num[i - 1]), pos[i][j + 1] - pos[i][j]); g.addEdge(j + 1 + (i == 0 ? 0 : num[i - 1]), j + (i == 0 ? 0 : num[i - 1]), pos[i][j + 1] - pos[i][j]); } } for (ll i = 0; i < M; i++) { ll a, b, c; tie(a, b, c) = bridge[i]; g.addEdge((a == 0 ? 0 : num[a - 1]) + mps[a][b], num[a] + mps[a + 1][c], 0); } const ll s = mps[0][S]; const ll t = mps[N - 1][T] + (N == 1 ? 0 : num[N - 2]); vector dist(num[N - 1]); Dijkstra(g, s, dist); cout << (dist[t] == INF ? -1 : dist[t]) << endl; return 0; }