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
| #include <bits/stdc++.h>
#include "railroad.h"
using namespace std; using re = double; using ll = long long; using pii = pair<int, int>;
const int Inf = 1E9;
long long plan_roller_coaster(std::vector<int> s, std::vector<int> t) { int n; ll res = 0; s.push_back(Inf), t.push_back(1), n = s.size(); vector<int> val; for (const int &i : s) val.push_back(i); for (const int &i : t) val.push_back(i); sort(val.begin(), val.end()); int w = unique(val.begin(), val.end()) - val.begin(); vector<int> fa(w); iota(fa.begin(), fa.end(), 0); const auto gf = [&](auto &&self, const int &x) -> int { return x == fa[x] ? x : fa[x] = self(self, fa[x]); }; const auto mrg = [&](const int &x, const int &y) -> void { fa[gf(gf, x)] = gf(gf, y); }; const auto qry = [&](const int &x, const int &y) -> bool { return gf(gf, x) == gf(gf, y); }; vector<int> d(w); for (int i = 0; i < n; ++i) { s[i] = lower_bound(val.begin(), val.begin() + w, s[i]) - val.begin(); t[i] = lower_bound(val.begin(), val.begin() + w, t[i]) - val.begin(); ++d[s[i]], --d[t[i]], mrg(s[i], t[i]); } for (int i = 1; i < w; ++i) d[i] += d[i - 1]; for (int i = 0; i < w - 1; ++i) if (d[i] != 0) { mrg(i, i + 1); if (d[i] > 0) res += 1ll * d[i] * (val[i + 1] - val[i]); } struct Edge { int x, y, w; }; vector<Edge> e; for (int i = 0; i < w - 1; ++i) if (!qry(i, i + 1)) e.push_back({i, i + 1, val[i + 1] - val[i]}); sort(e.begin(), e.end(), [&](const Edge &x, const Edge &y) { return x.w < y.w; }); for (const auto &[x, y, w] : e) { if (qry(x, y)) continue; mrg(x, y), res += w; } return res; }
#ifdef CPH signed main() { const function<int(void)> read = []() -> int { int res = 0, f = 1, ch = getchar(); while (!isdigit(ch)) (ch == '-') && (f = 0), ch = getchar(); while (isdigit(ch)) res = res * 10 + (ch ^ 48), ch = getchar(); return f ? res : ~res + 1; }; int n = read(), m = read(); vector<int> s(n), t(n); for (int i = 0; i < n; ++i) s[i] = read(), t[i] = read(); printf("%lld\n", plan_roller_coaster(s, t)); return 0; } #endif
|