Advertisement
tepyotin2

Moo Network

Jun 10th, 2025
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6.  
  7. struct DSU{
  8.     vector<ll> p;
  9.     DSU(ll n){
  10.         p = vector<ll>(n, -1);
  11.     }
  12.     ll get(ll x){
  13.         if(p[x]<0){
  14.             return x;
  15.         }else{
  16.             return p[x] = get(p[x]);
  17.         }
  18.     }
  19.     bool same_set(ll x, ll y){
  20.         return get(x) == get(y);
  21.     }
  22.     bool unite(ll x, ll y){
  23.         x = get(x);
  24.         y = get(y);
  25.         if(x == y) return false;
  26.         if(p[x]<p[y]) swap(p[x], p[y]);
  27.         p[x]+=p[y];
  28.         p[y] = x;
  29.         return true;
  30.     }
  31. };
  32.  
  33. struct Coor{
  34.     ll x, y;
  35.     bool operator<(const Coor &a) const{
  36.         if(x==a.x){
  37.             return y<a.y;
  38.         }
  39.         return x<a.x;
  40.     }
  41. };
  42.  
  43. struct Con{
  44.     ll a;
  45.     ll b;
  46.     ll cost;
  47.     bool operator<(const Con &a) const{
  48.         return cost<a.cost;
  49.     }
  50. };
  51.  
  52. ll n;
  53. vector<Con> con;
  54. ll ans;
  55.  
  56. int main(){
  57.     //freopen("moonetwork.in", "r", stdin);
  58.    
  59.     cin >> n;
  60.     vector<Coor> cd(n);
  61.     //must be n not n+1 because if n+1 then when sorted the values get shifted to the
  62.     //right which result in wrong answer
  63.     for(ll i=0; i<n; i++){
  64.         //int x, y;
  65.         cin >> cd[i].x >> cd[i].y;
  66.     }
  67.     //need to sort to make the values right to use for calculation
  68.     sort(cd.begin(), cd.end());
  69.     vector<ll> last(11, -1);
  70.     //different type of calculation depending on y because y is within 0-10 so can be
  71.     //used while previous looping of n*n would result in run time problem
  72.     for(ll i=0; i<n; i++){
  73.         for(ll j=0; j<=10; j++){
  74.             if(last[j] != -1){
  75.                 ll v = last[j];
  76.                 ll cost = ((cd[i].x-cd[v].x)*(cd[i].x-cd[v].x))+((cd[i].y-cd[v].y)*(cd[i].y-cd[v].y));
  77.                 con.push_back({i, v, cost});
  78.             }
  79.         }
  80.         last[cd[i].y] = i;
  81.     }
  82.     sort(con.begin(), con.end());
  83.     DSU dsu(n+1);
  84.     int count = 0;
  85.     for(ll i=0; i<con.size(); i++){
  86.         if(!dsu.same_set(con[i].a, con[i].b)){
  87.             dsu.unite(con[i].a, con[i].b);
  88.             ans+=con[i].cost;
  89.             count++;
  90.         }
  91.         if(count == n-1){
  92.             break;
  93.         }
  94.     }
  95.     cout << ans << '\n';
  96.    
  97.     return 0;
  98. }
  99.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement