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.
voidbfs(intstart,unordered_map<int,vector<int>>&adjList,unordered_set<int>&vis){queue<int>pq;pq.push(start);vis.insert(start);while(!pq.empty()){autonode=pq.front();pq.pop();for(autonbs:adjList[node]){if(vis.find(nbs)==vis.end()){vis.insert(nbs);pq.push(nbs);}}}}longroadsAndLibraries(intn,intc_lib,intc_road,vector<vector<int>>cities){//edge case c_lib < c_road therefor, it is optimal to build the lib for each cityif(c_lib<=c_road)returnstatic_cast<long>(n)*c_lib;unordered_map<int,vector<int>>adjList;// build adjListfor(autoct:cities){adjList[ct[0]].push_back(ct[1]);adjList[ct[1]].push_back(ct[0]);}// unvisited listunordered_set<int>vis;longcost=0;intregion=0;// traversal all cityfor(inti=1;i<=n;i++){if(vis.find(i)==vis.end()){cost+=static_cast<long>(c_lib);region++;// find out all connected path to current ctybfs(i,adjList,vis);}}// calculate final cost// total path = (cities -1) - (region -1) = cities - regioncost+=(vis.size()-region)*static_cast<long>(c_road);returncost;}
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++. The problem could be solved by BFS