In this Leetcode HackerEarth problem solution On a website, there are M users and they want to change their names. You will be given M lines consisting of two strings A and B, where username A wants to change his username to B. But the website does not support multiple users with the same username that is No two users can have the same username at the same time. A user can change his username from his current name to any name (X) if there is no user named X.
Every change in the username costs 1 unit of money. Find minimum cost to achieve these changes.


HackerEarth A website problem solution


HackerEarth A website problem solution.

#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mod 1000000007
#define endl "\n"
#define test ll txtc; cin>>txtc; while(txtc--)
typedef long long int ll;
class dsu{
    public:
    vector<ll>par;
    dsu(ll n){
        par.resize(n);
        iota(par.begin(),par.end(),0);
    }
    ll get(ll x){
        return (par[x]==x?x:(par[x]=get(par[x])));
    }
    bool unite(ll x,ll y){
        x=get(x);
        y=get(y);
        if(x!=y){
            par[x]=y;
            return true;
        }
        return false;
    }
};
int main() {
    FIO;
    test
    {
      ll n,m,ans=0,x,y;
      cin>>m; n=2*m;
      vector<pair<string,string>>vp(m);
      map<string,ll>mp;
      ll cnt=0;
      for(int i=0;i<m;i++){
          cin>>vp[i].first>>vp[i].second;
          if(mp.find(vp[i].first)==mp.end()){
              mp[vp[i].first]=cnt++;
          }
          if(mp.find(vp[i].second)==mp.end()){
              mp[vp[i].second]=cnt++;
          }
      }
      dsu d(n);
      for(int i=0;i<m;i++){
          x=mp[vp[i].first];
          y=mp[vp[i].second];
          if(x==y){
              continue;
          }
          ans+=1;
          if(!d.unite(x,y)){
              ans++;
          }
      }
      cout<<ans<<endl;
    }
    return 0;
}

Second solution

t = int(input())
while t > 0:
    t -= 1
    m = int(input())
    names = set()
    g = {}
    ans = 0
    for i in range(m):
        a, b = input().split()
        ans += a != b
        names.update([a, b])
        g[a] = b
    done = set()
    for name in names:
        if name in done or name not in g or g[name] == name:
            continue
        was = name
        while name not in done and name in g:
            done.add(name)
            name = g[name]
        ans += was == name
    print(ans)