Problem Link: https://onlinejudge.org/external/106/10685.pdf
Note: This problem is the basic application of the Union-Find algorithm. With the slight input manipulation, it is actually pretty similar to the problem UVa – 10608 – Friends. Just like that problem, this problem can be solved with approach 2 mentioned in the “Friends” problem, but I prefer approach 1.
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 n,m;
while(cin>>n>>m)
{
if(n==0 && m==0) break;
vector<int> root(n), ranking(n);
unordered_map<string,int> ump;
int c=0;
for(int i=0; i<n; i++)
{
root[i]=i;
ranking[i]=1;
string s;
cin>>s;
ump[s]=c;
c++;
}
for(int i=0; i<m; i++)
{
string s1, s2;
cin>>s1>>s2;
Union(ump[s1], ump[s2], root, ranking);
}
int ans=-1;
for(int i=0; i<n; i++)
{
ans=max(ranking[i], ans);
}
cout<<ans<<endl;
}
return 0;
}
One thought on “UVa – 10685 – Nature”