#include #include #include #include #include #include #include #include "math.h" using namespace std; typedef long long ll; struct P { bool operator<(const P& p) const { return b < p.b; } int b, c; ll val; }; struct Prev { bool operator<(const Prev& p) const { return c < p.c; } int b, c; ll val; }; int main() { ll MAX = LLONG_MAX / 2; ll N, M, K, S, T; cin >> N >> M >> K >> S >> T; vector > R(N - 1, vector

()); for (int i = 0; i < M; ++i) { P p; int a; cin >> a >> p.b >> p.c; p.val = MAX; R[a - 1].push_back(p); } vector prevs = vector(); Prev prev = {0, S, 0}; prevs.push_back(prev); for (int i = 0; i < N - 1; ++i) { sort(R[i].begin(), R[i].end()); int k_max = prevs.size() - 1; int k = 0; ll min_val = MAX; for (int j = 0; j < R[i].size(); ++j) { while (k <= k_max && prevs[k].c <= R[i][j].b) { min_val = min(min_val, prevs[k].val - prevs[k].c); k++; } R[i][j].val = min(R[i][j].val, min_val + R[i][j].b); } k = k_max; min_val = MAX; for (int j = R[i].size() - 1; j >= 0; --j) { while (k >= 0 && prevs[k].c >= R[i][j].b) { min_val = min(min_val, prevs[k].val + prevs[k].c); k--; } R[i][j].val = min(R[i][j].val, min_val - R[i][j].b); } prevs.clear(); for (int j = 0; j < R[i].size(); ++j) { Prev prev = {R[i][j].b, R[i][j].c, R[i][j].val}; prevs.push_back(prev); } sort(prevs.begin(), prevs.end()); } ll ans = MAX; for (int j = 0; j < prevs.size(); ++j) { ans = min(ans, abs(prevs[j].c - T) + prevs[j].val); } if (ans < MAX) { cout << ans << endl; } else { cout << -1 << endl; } }