Easy DFS solution
Complexity
Time complexity:  O(n)

Space complexity: O(n)
Code
# Complexity
- Time complexity:  $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: $$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```cpp []
class Solution {
public:
    vector<int> adj[100009];
    int cost[100009], vis[100009], And[100009];
    void dfs(int node, int id) {
        cost[id]&=And[node];
        vis[node]=id;
        for (auto it:adj[node]) if (!vis[it]) dfs(it, id);
    }
    vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
        memset(vis, 0, sizeof vis);
        memset(cost, -1, sizeof cost);
        memset(And, -1, sizeof And);
        for (auto it:edges) {
            adj[it[0]].push_back(it[1]);
            adj[it[1]].push_back(it[0]);
            And[it[0]]&=it[2];
            And[it[1]]&=it[2];
        }
        for (int i=0, id=1; i<n; i++) {
            if (!vis[i]) {
                dfs(i, id);
                id++;
            }
        }
        vector<int> ans;
        for (auto it:query) {
            if (vis[it[0]] != vis[it[1]]) ans.push_back(-1);
            else ans.push_back(cost[vis[it[0]]]);
        }
        return ans;
    }
};
```
['C++']