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.
longdfs(map<int,vector<int>>&paths,vector<bool>&visited,intcurrent){// initialize node count to 1intnode_count=1;// set this current position in the visited array to truevisited[current]=true;// iterate through the paths and dfs all non visited nodes/integersfor(autoit=paths[current].begin();it!=paths[current].end();it++){if(!visited[*it]){// add the return value of dfs to the node countnode_count+=dfs(paths,visited,*it);}}returnnode_count;}
roadsAndLibraries FUNC
longroadsAndLibraries(intn,intc_lib,intc_road,vector<vector<int>>cities){// initialize answerlonglonganswer=0;longlongextra_costs=0;longlongtotal_components=0;// rename constantsintcost_library=c_lib;intcost_road=c_road;intnumber_cities=n;intpaths_given=cities.size();// build our adjacency map, bidirectionalmap<int,vector<int>>paths;for(inti=0;i<cities.size();i++){intx=cities[i][0];inty=cities[i][1];paths[x].push_back(y);paths[y].push_back(x);}// build our visited vector, initialize to falsevector<bool>visited(n,false);// iterate over the adjacency map and for(autoit=paths.begin();it!=paths.end();it++){if(!visited[it->first]){intcomponent_size=dfs(paths,visited,it->first);total_components+=component_size;answer+=min((((component_size-1)*(cost_road))+(cost_library)),((component_size)*(cost_library)));}}if(n>total_components){extra_costs=(n-total_components)*cost_library;}returnanswer+extra_costs;}
Roads and Libraries
You are viewing a single comment's thread. Return to all comments →
C++ Solution DFS FUNC
roadsAndLibraries FUNC