Problem solution · C++

CCC 2018 S5 - Maximum Strategic Savings

CCC 2018 S5 - Maximum Strategic Savings: a C++ solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to CCCSolutions.

Technique
Disjoint set union
Source
CCCSolutions
Length
71 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For CCC 2018 S5 - Maximum Strategic Savings, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. 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.

Source

Code and credit

This code comes from CCCSolutions by CCCSolutions contributors · Milliken Mills High School and is used under the MIT licence.

Full codeCCC 2018 S5 - Maximum Strategic Savings · C++C++
Use this to learn the idea, then write your own version.
/*CCC '18 S5 - Maximum Strategic SavingsAuthor: Dan ShanDate: 2025-05-25Observation: Only need one portal per planet and one plane per city2d grid with planets as rows and cities as columns1. Kruskal's MST -> minimum in a row and multiply the number of *remaining* columns2.         minimum in a column and multiply by the number of *remaining* rowsNote: The 2 dimensions must be processed together to ensure optimal paths (*remaining* cols and rows are important)Subtract the MST weight from the original weight to find the maximum reduction*/#include <bits/stdc++.h>typedef long long ll;using namespace std;class ds{ // Disjoint set template	std::vector<int> p; // parentpublic:	ds() = default; // allows creation without initializing to vairables	explicit ds(int n){ // constructs a disjoint set		p.resize(n);		for(int i=0;i<n;i++){			p[i] = i;		}	}	int f(int i){		if(i!=p[i]){			p[i] = f(p[i]); // find parent using DFS		}		return p[i];	}	void us(int x, int y){ // union		p[f(x)] = f(y);	}};int main() {  ios::sync_with_stdio(false);  cin.tie(nullptr);  int n,m,p,q;  cin >> n >> m >> p >> q;  ll res=0;  ds row(n+1),col(m+1);  priority_queue<tuple<ll,ll,ll,ll>,vector<tuple<ll,ll,ll,ll>>,greater<>> pq;  while(p--){ // Columns    ll ai,bi,ci;    cin >> ai >> bi >> ci;    pq.push({ci,0,ai,bi});    res+=(ll)ci*n;  }  while(q--){ // Columns    ll ai,bi,ci;    cin >> ai >> bi >> ci;    pq.push({ci,1,ai,bi});    res+=(ll)ci*m;  }  while(pq.size()){    auto x=pq.top(); pq.pop();    ll ci=get<0>(x),ti=get<1>(x),ai=get<2>(x),bi=get<3>(x);    if(ti){      if(row.f(ai)==row.f(bi)) continue; // conncted      res-=ci*m; n--;      row.us(ai,bi);    }    else{      if(col.f(ai)==col.f(bi)) continue; // conncted      res-=ci*n; m--;      col.us(ai,bi);    }  }  cout << res << "\n";} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗