Advertisement
SalmaYasser

Untitled

Oct 26th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1.  
  2. int minCost (int n ,vector < vector <int> > &edg, vector < vector <int> > &newe)
  3. {
  4. vector < pair <int ,int> > adj [n+1];
  5. //vector <vector <bool> > broken (n+1, vector <bool> (n+1,false));
  6. for (int i = 0 ; i < newe.size(); i++)
  7. {
  8. int x , y,w;
  9. x= newe[i][0];
  10. y = newe[i][1];
  11. w = newe[i][2];
  12.  
  13. // broken[x][y]= true;
  14. // broken[y][x]=true;
  15.  
  16. adj[x].push_back({y,w});
  17. adj[y].push_back({x,w});
  18.  
  19. }
  20.  
  21. for (int i = 0 ; i < edg.size(); i++)
  22. {
  23.  
  24. int x , y;
  25. x= edg[i][0];
  26. y = edg[i][1];
  27. // if (broken[x][y])continue;
  28.  
  29. adj[x].push_back({y,0});
  30. adj[y].push_back({x,0});
  31. }
  32.  
  33.  
  34. priority_queue < pair <int, int> , vector < pair <int , int> > , greater < pair<int , int> > > q;
  35.  
  36. vector <bool> vis (n,false);
  37.  
  38. q.push({0,1});
  39.  
  40. int ans = 0;
  41. while (!q.empty())
  42. {
  43.  
  44. pair <int, int> cur = q.top();
  45. q.pop();
  46.  
  47. int val = cur.second;
  48. int cost = cur.first;
  49. if (vis[val])
  50. continue;
  51. ans+=cost;
  52. vis[val]= true;
  53.  
  54. for (auto x : adj[val])
  55. {
  56. int y = x.first;
  57. int w = x.second;
  58. if(!vis[y])
  59. q.push({w,y});
  60. }
  61. }
  62.  
  63. return ans;
  64.  
  65.  
  66. }
  67.  
  68.  
  69. int main() {
  70.  
  71. /*
  72. {{1, 2}, {2, 3}, {3, 4},{4,5},{1,6}{2,4}}
  73. {{1, 6, 410}, {2, 4, 800}, {1, 5, 8}}
  74.  
  75. [[1, 2], [2, 3], [4, 5], [3, 5], [1, 6], [2, 4]]
  76. [[1, 6, 410], [2, 4, 800]]
  77. */
  78. int n = 6;
  79. vector < vector <int> > edges ={{1, 4}, {4, 5}, {2, 3}};
  80. vector < vector <int> > newEdges = {{1, 2, 5}, {1, 3, 10}, {1, 6, 2}, {5, 6, 5}};
  81. cout<<(minCost(n, edges, newEdges));
  82.  
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement