Video Explanation (2 solutions - with and without DSU)
Explanation\n\nClick here for the video\n\n# Code\n\nstruct DSU {\n    vector<int> p, sz;\n    \n    DSU(int n) {\n        p.resize(n+1);\n        sz.resize(n+1
# Explanation\n\n[Click here for the video](https://youtu.be/E8Jj4F4U9VY)\n\n# Code\n```\nstruct DSU {\n    vector<int> p, sz;\n    \n    DSU(int n) {\n        p.resize(n+1);\n        sz.resize(n+1, 1);\n        \n        for (int j = 0; j <= n; j ++) p[j] = j;\n    }\n    \n    int Leader (int x) {\n        if (x == p[x]) return x;\n        return (p[x] = Leader(p[x]));\n    }\n    \n    void Merge (int x, int y) {\n        x = Leader(x);\n        y = Leader(y);\n        \n        if (x == y) return;\n        if (sz[x] > sz[y]) swap(x, y);\n        \n        sz[y] += sz[x];\n        p[x] = y;\n    }\n};\n\nclass Solution {\npublic:\n    vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {\n        DSU dsu(n);\n        for (auto e : edges) dsu.Merge (e[0], e[1]);\n            \n        vector<int> leader_val(n, -1);\n        for (auto e : edges) {\n            int x = dsu.Leader(e[0]);\n            int y = dsu.Leader(e[1]);            \n            assert (x == y);\n            \n            if (leader_val[x] == -1) leader_val[x] = e[2];\n            else leader_val[x] &= e[2];\n        }\n                \n        vector<int> ans;\n        for (auto q : query) {\n            if (q[0] == q[1]) {\n                ans.push_back(0);\n                continue;\n            }\n            int x = dsu.Leader(q[0]);\n            int y = dsu.Leader(q[1]);\n            \n            if (x != y) ans.push_back(-1);\n            else ans.push_back(leader_val[x]);            \n        }\n        return ans;\n    }\n};\n```
['C++']