public void MakeSet(Subset[] subsets) { for (int i = 1; i < subsets.Length; i++) { subsets[i] = new Subset(); subsets[i].Parent = i; subsets[i].Rank = 0; } }
public static int getMinimumCostToConstruct(int n, List <List <int> > edges, List <List <int> > newEdges) { if (n == 0) { return(0); } HashSet <int> hs = new HashSet <int>(); var edgeList = new List <(int, int, int)>(); DisJointSets djs = new DisJointSets(); Subset[] subsets = new Subset[n + 1]; int totalCost = 0; //get all the edges from the adjecency list foreach (var item in edges) { edgeList.Add((item[0], item[1], 0)); edgeList.Add((item[1], item[0], 0)); hs.Add(item[0]); hs.Add(item[1]); } foreach (var newIitem in newEdges) { edgeList.Add((newIitem[0], newIitem[1], newIitem[2])); edgeList.Add((newIitem[1], newIitem[0], newIitem[2])); hs.Add(newIitem[0]); hs.Add(newIitem[1]); } //All nodes are not connected by the available edges; //if (hs.Count != n) return -1; edgeList.Sort((a, b) => a.Item3 - b.Item3); djs.MakeSet(subsets); foreach (var edge in edgeList) { int x = djs.FindSet(subsets, edge.Item1); int y = djs.FindSet(subsets, edge.Item2); //exclude the edge if the reperesenting vertex is equal //it means there is a cycle so do not need to include in spanning tree if (x != y) { totalCost += edge.Item3; djs.Union(subsets, x, y); } } return(totalCost); }