C++ || O(n) || Beats 100% || Single Iteration || Union-Find
Complexity
Time complexity: O(edges.size() + n)

Space complexity: O(n)
Code


# Complexity
- Time complexity: O(edges.size() + 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> uf;
    int find(int x)
    {
        return x==uf[x]?x:(uf[x]=find(uf[x]));
    }

    vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
        vector<int> ret;
        vector<int> ands(n, INT_MAX);

        for(int i=0;i<n;i++)
            uf.push_back(i);

        for(auto &e:edges)
        {
            ands[find(e[1])] &= ands[find(e[0])] & e[2];
            uf[find(e[0])]=find(e[1]);
        }

        for(auto &q:query)
            ret.push_back(find(q[0])==find(q[1])?ands[find(q[1])]:-1);

        return ret;
    }
};
```
['Union Find', 'C++']