AtCoder-arc076_b.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <numeric>
  4. #include <tuple>
  5. #include <vector>
  6. using namespace std;
  7. struct DSU {
  8. vector<int> p, size;
  9. explicit DSU(int n) : p(n), size(n, 1) { iota(p.begin(), p.end(), 0); }
  10. int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }
  11. bool unite(int a, int b) {
  12. a = find(a); b = find(b); if (a == b) return false;
  13. if (size[a] < size[b]) swap(a, b); p[b] = a; size[a] += size[b]; return true;
  14. }
  15. };
  16. int main() {
  17. ios::sync_with_stdio(false);
  18. cin.tie(nullptr);
  19. int n; cin >> n;
  20. vector<long long> x(n), y(n); vector<int> order(n);
  21. for (int i = 0; i < n; ++i) cin >> x[i] >> y[i], order[i] = i;
  22. vector<tuple<long long, int, int>> edges;
  23. auto add_neighbors = [&](const vector<long long> &coordinate) {
  24. sort(order.begin(), order.end(), [&](int a, int b) { return coordinate[a] < coordinate[b]; });
  25. for (int i = 1; i < n; ++i) {
  26. int u = order[i - 1], v = order[i];
  27. edges.push_back({min(abs(x[u] - x[v]), abs(y[u] - y[v])), u, v});
  28. }
  29. };
  30. add_neighbors(x); add_neighbors(y);
  31. sort(edges.begin(), edges.end());
  32. DSU dsu(n); long long answer = 0;
  33. for (auto [w, u, v] : edges) if (dsu.unite(u, v)) answer += w;
  34. cout << answer << '\n';
  35. }