Problem Link: https://onlinejudge.org/external/115/11503.pdf
Note: This is another problem that is basically using the “ranking” property of the Union-Find algorithm.
Since the ranking vector of this code basically contains the “number of total nodes” connected to the root node at any time we are calling the Union() function, just returning that value whenever we are calling the Union() function will be our desired answer.
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);
}
int 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];
return ranking[rootX];
}
else
{
root[rootX]=rootY;
ranking[rootY]+=ranking[rootX];
return ranking[rootY];
}
}
return ranking[rootX];
}
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int t;
cin>>t;
while(t--)
{
int m;
cin>>m;
vector<int> root(100005), ranking(100005);
for(int i=0; i<100005; i++)
{
root[i]=i;
ranking[i]=1;
}
unordered_map<string, int> ump;
int c=0;
for(int i=0; i<m; i++)
{
string s1,s2;
cin>>s1>>s2;
if(!ump.count(s1))
{
ump[s1]=c;
c++;
}
if(!ump.count(s2))
{
ump[s2]=c;
c++;
}
cout<<Union(ump[s1],ump[s2], root, ranking)<<endl;
}
}
return 0;
}
One thought on “UVa – 11503 – Virtual Friends”