How to find MST for each source
Here is a slight modification of Kruskal's algorithm which can solve this.

Sort all edges by non-decreasing weight.
Maintain a disjoint set union to track which vertices are connected, as usual.
Consider the edges one by one in the resulting order.
If an edge connects two vertices which are already connected, we drop it, as usual.

The difference is as follows: if an edge connects two components such that each already contains a factory, such edge would contribute nothing to our network, so we also drop it.

If an edge connects two components, and at least one of them does not contain a factory, we take the edge and update the disjoint set union, as usual.



Another view with the same result is as follows.
Make an auxiliary vertex, the super-factory.
Add an edge of weight 0 from the super-factory to each of the real factories.
Run Kruskal algorithm on this new graph.

First thing, it will take all our added edges with weight 0.
If the original graph also had such edges, let the algorithm start with our newly added edges. We can do it since the total cost does not depend on the ordering of same-weight edges.

Now, the original condition &ldquo;each shop must be connected to a factory&rdquo; got translated to &ldquo;each shop must be connected to the super-factory&rdquo;, which is equivalent to just &ldquo;all vertices must be connected&rdquo;, which in turn is exactly what Kruskal algorithm will do for us.