Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int makeConnected(int n, vector<vector<int>>& connections) {
- int wiresAvailaible = connections.size();
- vector<int> visited(n,0);
- vector<vector<int>> edges(n);
- int maxNode=0;
- for(auto connection:connections) {
- int from = connection[0];
- int to = connection[1];
- edges[from].push_back(to);
- //edges[to].push_back(from);
- maxNode = max(maxNode,from);
- maxNode = max(maxNode,to);
- }
- priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>> pq;
- pq.push({1,{edges[0][0],-1}});// weight , node, parent
- int wiresUsed=0;
- while(!pq.empty()) {
- auto temp = pq.top();
- pq.pop();
- int node = temp.second.first;
- if(visited[node]) continue;
- visited[node]=1;
- int parent = temp.second.second;
- wiresUsed+=1;
- for(auto n:edges[node]) {
- if(visited[n]==0) {
- pq.push({1,{n,node}});
- // visited[n]=1;
- }
- }
- }
- int extraWires = wiresAvailaible-wiresUsed;
- int nodesLeftOut =n-(maxNode+1);
- int renovationsRequired = nodesLeftOut;
- if (extraWires>=renovationsRequired) return nodesLeftOut;
- return -1;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement