You are counting for the number of elements in the set after each query... that is not efficient.
You can hold an array num_elements[N] which contains the number of elements of each set (initially 1).
When you make the union, you can do something like:
Code: Select all
...
if(u!=v)
{
par[u]=v;
num_elements[v] += num_elements[u];
}
then, you can get the number of elements in constant time with num_elements[find(M[name_1])]
or even better, your union function could return that value.