Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
- vector<vector<pair<int,int>>> g(n);
- map<pair<int,int>,int> mp;
- for(int i = 0;i < edges.size();i += 1){
- int u = edges[i][0], v = edges[i][1], w = edges[i][2];
- if(u > v){
- swap(u, v);
- }
- // u < v
- if(mp.count({u, v})){
- mp[{u, v}] &= w;
- }
- else{
- mp[{u, v}] = w;
- }
- }
- for(auto &x : mp){
- int u = x.first.first, v = x.first.second;
- int w = x.second;
- // cout << u << ' ' << v << ' ' << w << endl;
- g[u].push_back({v, w});
- g[v].push_back({u, w});
- }
- vector<int> vis(n);
- vector<int> cmp;
- queue<int> q;
- function<void(int,int &)> bfs = [&](int cur, int &val){
- q.push(cur);
- while(!q.empty()){
- cur = q.front();
- q.pop();
- vis[cur] = 1;
- cmp.push_back(cur);
- // cur <----> x
- // x ---> cur
- for(auto [x, w] : g[cur]){
- val &= w;
- if(!vis[x]){
- q.push(x);
- }
- }
- }
- };
- vector<int> ans(n);
- vector<int> id(n);
- int c = 0;
- for(int i = 0;i < n;i += 1){
- if(vis[i] == 0){
- int val = (1 << 30) - 1;
- bfs(i, val);
- for(auto &x : cmp){
- id[x] = c;
- ans[x] = val;
- }
- c += 1;
- cmp.clear();
- }
- }
- vector<int> res;
- for(auto &v : query){
- int x = v[0], y = v[1];
- // cout << ans[x] << ' ' << ans[y] << '\n';
- if(id[x] != id[y]){
- res.push_back(-1);
- }
- else res.push_back(ans[x]);
- }
- return res;
- }
- };
Add Comment
Please, Sign In to add comment