You are viewing a single comment's thread. Return to all comments →
long roadsAndLibraries(int n, int c_lib, int c_road, vector<vector<int>> cities) { if (cities.empty() || c_lib <= c_road) return (long)n * c_lib; map<int, stack<int>> cityMap; for (vector<int> road : cities) { int city1 = road[0], city2 = road[1]; cityMap[city1].push(city2); cityMap[city2].push(city1); } vector<bool> visited(n + 1, false); long libs = 0, rds = 0; for (int i = 1; i <= n; ++i) { if (!visited[i]) { libs++; stack<int> neighbors; neighbors.push(i); visited[i] = true; while (!neighbors.empty()) { int curr = neighbors.top(); neighbors.pop(); while (!cityMap[curr].empty()) { int neighbor = cityMap[curr].top(); cityMap[curr].pop(); if (!visited[neighbor]) { visited[neighbor] = true; neighbors.push(neighbor); rds++; } } } } } return libs * c_lib + rds * c_road; }
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 →