- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 71 lines of C++ from the credited upstream file ccc18s5.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected, together with recursive traversal.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/*2CCC '18 S5 - Maximum Strategic Savings3Author: Dan Shan4Date: 2025-05-255Observation: Only need one portal per planet and one plane per city62d grid with planets as rows and cities as columns71. Kruskal's MST -> minimum in a row and multiply the number of *remaining* columns82. minimum in a column and multiply by the number of *remaining* rows9Note: The 2 dimensions must be processed together to ensure optimal paths (*remaining* cols and rows are important)10Subtract the MST weight from the original weight to find the maximum reduction11*/12#include <bits/stdc++.h>13typedef long long ll;14using namespace std;15class ds{ 16 std::vector<int> p; 17public:18 ds() = default; 19 explicit ds(int n){ 20 p.resize(n);21 for(int i=0;i<n;i++){22 p[i] = i;23 }24 }25 int f(int i){26 if(i!=p[i]){27 p[i] = f(p[i]); 28 }29 return p[i];30 }31 void us(int x, int y){ 32 p[f(x)] = f(y);33 }34};35int main() {36 ios::sync_with_stdio(false);37 cin.tie(nullptr);38 int n,m,p,q;39 cin >> n >> m >> p >> q;40 ll res=0;41 ds row(n+1),col(m+1);42 priority_queue<tuple<ll,ll,ll,ll>,vector<tuple<ll,ll,ll,ll>>,greater<>> pq;43 while(p--){ 44 ll ai,bi,ci;45 cin >> ai >> bi >> ci;46 pq.push({ci,0,ai,bi});47 res+=(ll)ci*n;48 }49 while(q--){ 50 ll ai,bi,ci;51 cin >> ai >> bi >> ci;52 pq.push({ci,1,ai,bi});53 res+=(ll)ci*m;54 }55 while(pq.size()){56 auto x=pq.top(); pq.pop();57 ll ci=get<0>(x),ti=get<1>(x),ai=get<2>(x),bi=get<3>(x);58 if(ti){59 if(row.f(ai)==row.f(bi)) continue; 60 res-=ci*m; n--;61 row.us(ai,bi);62 }63 else{64 if(col.f(ai)==col.f(bi)) continue; 65 res-=ci*n; m--;66 col.us(ai,bi);67 }68 }69 cout << res << "\n";70}71