Simple BFS | No DSU | Easy to understand + Video Explanation | C++
Approach\nJust maintain an array of ids to check if 2 nodes lie in the same connected component or not.\nFor answer its always minimum when you traverse all the
# Approach\nJust maintain an array of ids to check if 2 nodes lie in the same connected component or not.\nFor answer its always minimum when you traverse all the edges in the connected component of source and target nodes because bitwise and is a decreasing function.\n\n# Video Explanation\nhttps://www.youtube.com/watch?v=ej1ViCisA1o\n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {\n        vector<vector<pair<int,int>>> g(n);\n        for(auto x: edges){\n            g[x[0]].push_back(make_pair(x[1],x[2]));\n            g[x[1]].push_back(make_pair(x[0],x[2]));\n        }\n        vector<int> comp(n);\n        vector<int> answers(2*n);\n        vector<bool> vis(n, false);\n        queue<int> q;\n        int id = 0;\n        \n        for(int i=0;i<n;i++){\n            if(!vis[i]){\n                q.push(i);\n                vis[i]=true;\n                int ans = -1;\n                set<pair<int,int>> viss;\n                while(!q.empty()){\n                    int tp = q.front();\n                    comp[tp]=id;\n                    q.pop();\n                    for(auto x: g[tp]){\n                        if(viss.count(x)==0){\n                            vis[x.first]=true;\n                            if(ans==-1){\n                                ans=x.second;\n                            } else {\n                                ans&=x.second;\n                            }\n                            q.push(x.first);\n                            viss.insert(x);\n                        }\n                    }\n                }\n                answers[id]=ans;\n                ++id;   \n            }\n        }\n        vector<int> ret;\n        for(auto x: query){\n            if(x[0]==x[1]){\n                ret.push_back(0);\n            }\n            else if(comp[x[0]]==comp[x[1]]){\n                ret.push_back(answers[comp[x[0]]]);\n            } else {\n                ret.push_back(-1);\n            }\n        }\n        return ret;\n    }\n};\n```
['C++']