1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| #pragma warning (disable:4996) #include <iostream> #include <cstdio> #include <cstring> #include <deque> #include <queue> #include <vector> #include <algorithm> using namespace std; const int maxn = 2e5 + 5, maxm = 4e5 + 5, inf = 0x7fffffff; int head[maxm], nxt[maxm], v[maxm], w[maxm], h[maxn], x[maxn], y[maxn], dis[maxn]; bool vis[maxn]; int n, m, cnt, sx, sy;
inline void addline(int x, int y, int z) { v[cnt] = y, w[cnt] = z, nxt[cnt] = head[x], head[x] = cnt++; }
inline int read() { register int x = 0; register char c = getchar(); while (c<'0' || c>'9') c = getchar(); while (c >= '0'&&c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar(); return x; }
inline void qsort(int l, int r) { register int mid = h[(l + r) >> 1], L = l, R = r; while (l <= r) { while (h[l] > mid) l++; while (h[r] < mid) r--; if (l <= r) { swap(h[l], h[r]), swap(x[l], x[r]), swap(y[l], y[r]), l++, r--; } } if (L < r) qsort(L, r); if (l < R) qsort(l, R); return; }
inline void connect() { addline(0, 1, sy - h[1] + sx - x[1]), addline(0, n + 1, sy - h[1] + y[1] - sx); queue<int> Q; while (!Q.empty()) Q.pop(); Q.push(1); while (!Q.empty()) { int i = Q.front(); Q.pop(); bool left = false, right = false; for (int j = i + 1; h[i] > h[j] && h[i] - h[j] <= m && j <= n; j++) { if (!left && x[j] < x[i] && x[i] < y[j]) { addline(i, j, h[i] - h[j] + x[i] - x[j]); addline(i, j + n, h[i] - h[j] + y[j] - x[i]); left = true; if (!vis[j]) Q.push(j), vis[j] = true; } if (!right && x[j] < y[i] && y[i] < y[j]) { addline(i + n, j, h[i] - h[j] + y[i] - x[j]); addline(i + n, j + n, h[i] - h[j] + y[j] - y[i]); right = true; if (!vis[j]) Q.push(j), vis[j] = true; } if (left && right) break; } if (!left&&h[i] <= m) addline(i, n << 1 | 1, h[i]); if (!right&&h[i] <= m) addline(i + n, n << 1 | 1, h[i]); } return; }
inline void SPFA() { memset(dis, 0x3f, sizeof(dis)); memset(vis, 0, sizeof(vis)); deque<int> Q; while (!Q.empty()) Q.pop_back(); dis[0] = 0, Q.push_back(0), vis[0] = true; while (!Q.empty()) { int x = Q.front(); Q.pop_front(); vis[x] = false; for (register int i = head[x]; i != -1; i = nxt[i]) if (dis[v[i]] > dis[x] + w[i]) { dis[v[i]] = dis[x] + w[i]; if (!vis[v[i]]) { vis[v[i]] = true; if (!Q.empty()) { if (dis[v[i]] > dis[Q.front()]) Q.push_back(v[i]); else Q.push_front(v[i]); } else Q.push_back(v[i]); } } } return; }
int main() { memset(head, -1, sizeof(head)); n = read(), m = read(), sx = read(), sy = read(); for (int i = 1; i <= n; i++) h[i] = read(), x[i] = read(), y[i] = read(); qsort(1, n), connect(), SPFA(); printf("%d\n", dis[n << 1 | 1]); return 0; }
|