A website
Practice
3.6 (7 votes)
Data structures
Dsu
Basics of disjoint data structures
Disjoint data structures
Problem
90% Success 995 Attempts 50 Points 3s Time Limit 256MB Memory 1024 KB Max Code

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.

Notes

  • If user X wants to change his username from a to b while user Y wants to change his username from b to a neither of the users can directly change as if a changes his name to b now there will be two users having the username b.
  • If user X wants to change his username from a to a, so the user doesn't need to do anything.
  • It is guaranteed that no two users have the same username initially and no two users will have the same once all the changes are done.
  • It can be proved that the changes can always be done.

Input format

  • The first line consists of an integer \(T\) denoting the number of test cases.
  • The first line of each test case contains an integer \(M\) denoting the number of users.
  • Each of the next \(M\) lines of every test case contain two strings \(A\) and \(B\) where the \(i^{th}\) user wants to change his username from \(A\) to \(B\).

Output format

For each test case:

  • Print a single line denoting the minimum cost for completing the changes in usernames.

Constraints

  • \(1 \leq T \leq 20000\)
  • \(1 \leq M \leq 100000\)
  • Each string consists of lower case Latin letters and has a length between 5 and 10.
  • The sum of \(M\) over all test cases will not exceed 200000.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
Tags:
Data StructuresDisjoint Data StructuresDisjoint SetDisjoint setMediumpersistent segment tree
Points:50
2 votes
Tags:
Data StructuresDisjoint Data StructuresDisjoint SetMedium
Points:50
6 votes
Tags:
Dijkstra's AlgorithmMedium