#include #include #include #include #include using namespace std; #define int long long using int64 = long long; using P = pair; // (棟, 階) const int maxn = 300000; const int64 inf = (1LL << 60); map table[maxn]; map> G[maxn]; signed main() { cin.tie(0); ios::sync_with_stdio(false); int64 N, M, K, S, T; cin >> N >> M >> K >> S >> T; assert(1 <= N and N <= 200000); assert(0 <= M and M <= 200000); assert(1 <= K and K <= 1e9); assert(1 <= S and S <= K); assert(1 <= T and T <= K); for (int i = 0; i < M; i++) { int a, b, c; cin >> a >> b >> c; assert(1 <= a and a <= N - 1); assert(1 <= b and b <= K); assert(1 <= c and c <= K); a--; G[a][b].push_back(c); table[a][b] = inf; table[a + 1][c] = inf; } if (N == 1 and M == 0) { cout << abs(S - T) << endl; return 0; } for (auto& mp : table[N - 1]) mp.second = abs(T - mp.first); for (int i = N - 1; i >= 0; i--) { int64 val = inf; for (auto& p : table[i]) { for (int to : G[i][p.first]) { p.second = min(p.second, table[i + 1][to]); } p.second = min(p.second, val + p.first); val = min(val, p.second - p.first); } val = inf; for (auto it = table[i].rbegin(); it != table[i].rend(); it++) { it->second = min(it->second, val - it->first); val = min(val, it->second + it->first); } } int64 ans = inf; for (auto& mp : table[0]) ans = min(ans, mp.second + abs(S - mp.first)); if (ans >= inf / 2) cout << -1 << endl; else cout << ans << endl; return 0; }