Advertisement
Alex_tz307

USACO 2016 December Contest, Gold Problem 1. Moocast

Mar 13th, 2021
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define sqr(x) ((x) * (x))
  3.  
  4. using namespace std;
  5.  
  6. ifstream fin("moocast.in");
  7. ofstream fout("moocast.out");
  8.  
  9. class vertex {
  10.     public:
  11.         int x, y;
  12.  
  13.         void read() {
  14.             fin >> x >> y;
  15.         }
  16. };
  17.  
  18. class edge {
  19.     public:
  20.         int u, v, w;
  21.  
  22.         bool operator < (const edge &A) const {
  23.             return w < A.w;
  24.         };
  25. };
  26.  
  27. class DSU {
  28.     public:
  29.         int N;
  30.         vector<int> p, r;
  31.  
  32.         DSU(int n) : N(n) {
  33.             p.resize(N + 1), r.assign(N + 1, 1);
  34.             iota(p.begin(), p.end(), 0);
  35.         }
  36.  
  37.         int get(int x) {
  38.             return (x == p[x] ? x : (p[x] = get(p[x])));
  39.         }
  40.  
  41.         bool connected(int u, int v) {
  42.             int x = get(u),
  43.                 y = get(v);
  44.             return x == y;
  45.         }
  46.  
  47.         bool unite(int u, int v) {
  48.             int x = get(u),
  49.                 y = get(v);
  50.             if(x == y)
  51.                 return false;
  52.             if(r[x] == r[y])
  53.                 ++r[x];
  54.             if(r[x] > r[y]) {
  55.                 p[y] = x;
  56.                 r[x] += r[y];
  57.             }
  58.             else {
  59.                p[x] = y;
  60.                r[y] += r[x];
  61.             }
  62.             return true;
  63.         }
  64. };
  65.  
  66. const int NMAX = 1 << 10;
  67. const int EMAX = 1 << 20;
  68. int N, M, cnt;
  69. vertex a[NMAX];
  70. edge edges[EMAX];
  71.  
  72. int dist(const vertex &A, const vertex &B) {
  73.     return sqr(B.x - A.x) + sqr(B.y - A.y);
  74. }
  75.  
  76. int main() {
  77.     fin >> N;
  78.     for(int i = 1; i <= N; ++i)
  79.         a[i].read();
  80.     for(int i = 1; i < N; ++i)
  81.         for(int j = i + 1; j <= N; ++j)
  82.             edges[++M] = edge{i, j, dist(a[i], a[j])};
  83.     sort(edges + 1, edges + M + 1);
  84.     DSU tree(N);
  85.     for(int i = 1; i <= M; ++i)
  86.         if(!tree.connected(edges[i].u, edges[i].v)) {
  87.             ++cnt;
  88.             if(cnt == N - 1) {
  89.                 fout << edges[i].w << '\n';
  90.                 return 0;
  91.             }
  92.             tree.unite(edges[i].u, edges[i].v);
  93.         }
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement