stillnotred

Untitled

Mar 20th, 2025
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. class Solution {
  2. public:
  3.  
  4. vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
  5. vector<vector<pair<int,int>>> g(n);
  6.  
  7. map<pair<int,int>,int> mp;
  8.  
  9. for(int i = 0;i < edges.size();i += 1){
  10. int u = edges[i][0], v = edges[i][1], w = edges[i][2];
  11. if(u > v){
  12. swap(u, v);
  13. }
  14. // u < v
  15.  
  16. if(mp.count({u, v})){
  17. mp[{u, v}] &= w;
  18. }
  19. else{
  20. mp[{u, v}] = w;
  21. }
  22. }
  23.  
  24. for(auto &x : mp){
  25. int u = x.first.first, v = x.first.second;
  26. int w = x.second;
  27.  
  28. // cout << u << ' ' << v << ' ' << w << endl;
  29.  
  30. g[u].push_back({v, w});
  31. g[v].push_back({u, w});
  32.  
  33. }
  34.  
  35.  
  36. vector<int> vis(n);
  37. vector<int> cmp;
  38.  
  39. queue<int> q;
  40. function<void(int,int &)> bfs = [&](int cur, int &val){
  41. q.push(cur);
  42.  
  43. while(!q.empty()){
  44. cur = q.front();
  45. q.pop();
  46.  
  47. vis[cur] = 1;
  48.  
  49. cmp.push_back(cur);
  50.  
  51.  
  52. // cur <----> x
  53. // x ---> cur
  54.  
  55. for(auto [x, w] : g[cur]){
  56. val &= w;
  57.  
  58. if(!vis[x]){
  59. q.push(x);
  60. }
  61. }
  62. }
  63. };
  64.  
  65. vector<int> ans(n);
  66. vector<int> id(n);
  67.  
  68. int c = 0;
  69.  
  70. for(int i = 0;i < n;i += 1){
  71. if(vis[i] == 0){
  72. int val = (1 << 30) - 1;
  73.  
  74. bfs(i, val);
  75.  
  76. for(auto &x : cmp){
  77. id[x] = c;
  78. ans[x] = val;
  79. }
  80.  
  81. c += 1;
  82.  
  83. cmp.clear();
  84. }
  85. }
  86.  
  87. vector<int> res;
  88.  
  89. for(auto &v : query){
  90. int x = v[0], y = v[1];
  91.  
  92. // cout << ans[x] << ' ' << ans[y] << '\n';
  93.  
  94. if(id[x] != id[y]){
  95. res.push_back(-1);
  96. }
  97. else res.push_back(ans[x]);
  98.  
  99. }
  100.  
  101. return res;
  102. }
  103. };
Advertisement
Add Comment
Please, Sign In to add comment