Advertisement
Singasking

Untitled

Jun 29th, 2023
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int makeConnected(int n, vector<vector<int>>& connections) {
  4. int wiresAvailaible = connections.size();
  5. vector<int> visited(n,0);
  6. vector<vector<int>> edges(n);
  7. int maxNode=0;
  8. for(auto connection:connections) {
  9. int from = connection[0];
  10. int to = connection[1];
  11. edges[from].push_back(to);
  12. //edges[to].push_back(from);
  13. maxNode = max(maxNode,from);
  14. maxNode = max(maxNode,to);
  15.  
  16. }
  17.  
  18. priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>> pq;
  19.  
  20.  
  21. pq.push({1,{edges[0][0],-1}});// weight , node, parent
  22. int wiresUsed=0;
  23. while(!pq.empty()) {
  24. auto temp = pq.top();
  25. pq.pop();
  26.  
  27. int node = temp.second.first;
  28. if(visited[node]) continue;
  29. visited[node]=1;
  30. int parent = temp.second.second;
  31. wiresUsed+=1;
  32. for(auto n:edges[node]) {
  33. if(visited[n]==0) {
  34. pq.push({1,{n,node}});
  35. // visited[n]=1;
  36. }
  37. }
  38. }
  39.  
  40. int extraWires = wiresAvailaible-wiresUsed;
  41. int nodesLeftOut =n-(maxNode+1);
  42.  
  43.  
  44. int renovationsRequired = nodesLeftOut;
  45. if (extraWires>=renovationsRequired) return nodesLeftOut;
  46. return -1;
  47.  
  48. }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement