It'll be wonderful and really helpful if someone can give their solution along with an explanation of their approach.
Jenny is the mayor of a city named Water-7. The city is a bit special. It can be represented as an undirected graph having more than one connected components.
Each of the connected components may have their own single source of water supply. One major rule in Water-7 imposed by Jenny is that water from different components must never be mixed together. Being a really generous mayor, Jenny wants to install more pipes in each components so as to facilitate smooth circulation of water.
She wants to increase connections in each components by installing as much pipes as possible without breaking the rule. However connection of pipes is not easy and comes with a cost as well.
Jenny can connect cities within same components without any cost, only connecting cities within two different components requires a price that being the product of the respective sizes of their components.
(See sample for better explanation).
Jenny gives you the layout of water-7. Now she wants to know how many extra pipes she has to add and minimum total cost of doing so.
Input Format:
Output Format
Constraints
Sample Input
12 7 2
1 2
1 3
4 5
4 6
5 7
9 10
11 12
1 4Sample Output
32 28Explanation
The given graph consist of 5 connected components.
(1,2,3), (4,5,6,7), (8), (9,10), (11,12).
1 is the water supply point in (1,2,3) and 4 is the water supply point in (4,5,6,7).
There is no water supply point in (8), (9,10), (11,12).
For (1,2,3):-
We can add 1 edge from 2 to 3, cost = 0 (same component).
For (4,5,6,7):-
We will add 3 edges from 6 to 5, 6 to 7 and 4 to 7. Now we can't add more edges to this component, cost = 0 (same component).
For the remaining nodes (without water supply points):-
We will first connect (8) and with (11,12) cost 2 and 2 edges.
Then (8,11,12) and (9,10) with cost 6 and 6 edges. (product of their sizes).
Now we have all the non water supply points completely connected.
We can now connect all the 5 non water supply points to the component (4,5,6,7) with cost 20 and 20 edges.
Hence total cost is 28 and maximum number of edges that can be added are 32.