Saturday 26 November 2016

FOXLINGS - Foxlings - SOLUTION

I am assuming that you have already understood the problem statement otherwise go back and read the problem statement once again: PROBLEM STATEMENT

If you are not familiar with DSU and path compression, I suggest you to go and read this post first.

There are total N Foxlings , and if one foxling gets a cracker he divides it and give it to his friend too, in this way, if only one member of each friend circle receives a cracker, indirectly whole group will have crackers !

Input contains N the number of foxlings and M, the number of friendships.
Next M lines contains  A B , which means A is friend of B, and B is friend of A.

Initially, there is no friendship, so everyone is their own friend, and there are total N groups. Let us store number of groups in a variable co, i.e., co = N .
So, what we can do is , using union operation at each of the M queries, i.e., finding the root of A and B , and if root(A) ! = root (B) we will do union of them. And every time we do union, we will reduce value of co by one. After all queries the remaining value of co will be our answer!

I hope you can implement the code for this problem yourself otherwise refer to the following code:



2 comments:

  1. u can also modify your union method by considering the size of each subset. it will further optimize your code.

    ReplyDelete