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.
voidinsertCityToMap(std::map<long,vector<long>>&cityMap,int&cityNum1,int&cityNum2){std::map<long,vector<long>>::iteratorit=cityMap.find(cityNum1);if(it==cityMap.end()){//insert new vectorcityMap.insert(pair<long,vector<long>>(cityNum1,vector<long>{cityNum2}));}else{if(find(it->second.begin(),it->second.end(),cityNum2)==it->second.end())//sanity check incase of duplicateit->second.push_back(cityNum2);}}//arguments passed by referencevoidcityDfs(std::map<long,vector<long>>&cityMap,long&adj,std::vector<bool>&visited,long&minCost,int&c_road,int&count){minCost+=c_road;visited[adj]=true;count++;std::map<long,vector<long>>::iteratorit=cityMap.find(adj);std::vector<long>connectedCities=it->second;for(longlongi=0;i<connectedCities.size();i++){if(visited[connectedCities[i]]==false){cityDfs(cityMap,connectedCities[i],visited,minCost,c_road,count);}}}longroadsAndLibraries(intn,intc_lib,intc_road,vector<vector<int>>cities){if(c_lib<=c_road){returnlong(c_lib*n);}std::map<long,vector<long>>cityMap;std::vector<bool>visited(n+1,false);for(longi=0;i<cities.size();i++){insertCityToMap(cityMap,cities[i][0],cities[i][1]);insertCityToMap(cityMap,cities[i][1],cities[i][0]);}std::map<long,vector<long>>::iteratorit;longminCost=0;intcount=0;//to track the number of visted cities. This will help when identifying the number of standalone cities.//starting with a map node (city), it will build one library and DFS to complete the rest of the sub-map.for(it=cityMap.begin();it!=cityMap.end();it++){if(visited[it->first]==false){minCost+=c_lib;visited[it->first]=true;count++;for(longlongj=0;j<it->second.size();j++){if(visited[it->second[j]]==false){cityDfs(cityMap,it->second[j],visited,minCost,c_road,count);}}}}returnminCost+c_lib*(n-count);}
build the map based on the cities info.
iterate the map city by city, check the connected cities, and properly build the library and the roads for a complete sub map.
iterate the rest of the map and complete the algorithm.
Mine passes 0, 1, 2, 7, 11, 12.
The rest test cases with a huge input FAIL with wrong output. Not the time limit exceed.
Could anyone provide a hint what I might be missing?
Much appreciated!
Thanks
Roads and Libraries
You are viewing a single comment's thread. Return to all comments →
Mine passes 0, 1, 2, 7, 11, 12. The rest test cases with a huge input FAIL with wrong output. Not the time limit exceed. Could anyone provide a hint what I might be missing? Much appreciated! Thanks