We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classResult{// Uses the Union-Find algorithm to find the number of connected components.publicstaticlongroadsAndLibraries(intn,intc_lib,intc_road,List<List<int>>cities){if(c_lib<c_road){return(long)c_lib*n;}int[]parents=newint[n+1];// n+1 because cities are 1-indexed.// Init with each node as its own parent.for(inti=0;i<=n;i++){parents[i]=i;}foreach(List<int>edgeincities){Union(edge[0],edge[1],parents);}// Final round up. Now parents points to the root of each component.for(inti=0;i<=n;i++){parents[i]=Find(i,parents);}List<int>parentsList=parents.ToList();longcomponents=parentsList.Distinct().LongCount()-1;// -1 because parents[0] doesn't really exist.longedges=n-components;return(components*c_lib)+(edges*c_road);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Roads and Libraries
You are viewing a single comment's thread. Return to all comments →
C# solution using Union-Find Algorithm explained here: https://www.geeksforgeeks.org/introduction-to-disjoint-set-data-structure-or-union-find-algorithm/