Problem Link: https://onlinejudge.org/external/119/11966.pdf
Note: This problem is the basic implementation of the Union-Find problem.
Code:
#include <bits/stdc++.h>
using namespace std;
int Find(int x, vector<int> &root)
{
if(x==root[x]) return x;
return root[x]=Find(root[x], root);
}
void Union(int x, int y, vector<int> &root, vector<int> &ranking)
{
int rootX=Find(x, root);
int rootY=Find(y, root);
if(rootX!=rootY)
{
if(ranking[rootX]>=ranking[rootY])
{
root[rootY]=rootX;
ranking[rootX]+=ranking[rootY];
}
else
{
root[rootX]=rootY;
ranking[rootY]+=ranking[rootX];
}
}
}
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int t;
cin>>t;
for(int z=1; z<=t; z++)
{
int n;
double d;
cin>>n>>d;
vector<int> root(n), ranking(n);
for(int i=0; i<n; i++)
{
root[i]=i;
ranking[i]=1;
}
vector<pair<double, double> > v;
for(int i=0; i<n; i++)
{
double x,y;
cin>>x>>y;
v.push_back({x,y});
}
for(int i=0; i<n-1; i++)
{
double x1=v[i].first;
double y1=v[i].second;
for(int j=i+1; j<n; j++)
{
double x2=v[j].first;
double y2=v[j].second;
double dis=sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); //General formula of distance between two points on a 2D plane
if(dis<=d) Union(i, j , root, ranking);
}
}
int ans=0;
for(int i=0; i<n; i++)
{
if(root[i]==i) ans++;
}
cout<<"Case "<<z<<": "<<ans<<endl;
}
return 0;
}
One thought on “UVa – 11966 – Galactic Bonding”