✅✅ Classic DSU || Beginner Friendly ( If DSU studied ) || Easy Solution
IntuitionThe problem involves finding the minimum bitwise AND value between two nodes in a graph with weighted edges.
Since multiple nodes may be connected, Dis
# Intuition
The problem involves finding the minimum bitwise **AND** value between two nodes in a graph with weighted edges.  
Since multiple nodes may be connected, **Disjoint Set Union (DSU)** (Union-Find) is a suitable approach.

# Approach
1. **Initialize DSU**:
   - Create `parent` and `cost` arrays for `n` nodes.
   - Initially, each node is its own parent, and the cost is `-1`.

2. **Process Edges**:
   - For each `(u, v, w)`, find their parents.
   - If they belong to different components, merge them and update their cost using `&= w`.

3. **Answer Queries**:
   - If `s == t`, return `0`.
   - If `s` and `t` have different parents, return `-1`.
   - Otherwise, return the minimum AND value stored in `cost[parent[s]]`.

# Time Complexity
- **O(N + E + Q)**  
  - `O(N)` for initialization.
  - `O(E * α(N))` for edge processing using Union-Find (near constant time).
  - `O(Q * α(N))` for queries.

# Space Complexity
- **O(N)** for `parent` and `cost` arrays.

# Code
```cpp []
class Solution {
public:
    vector<int>parent;
    vector<int>cost;
    int find(int x){
        if(x==parent[x]) return x;
        return parent[x]=find(parent[x]);
    }
    void Union(int x,int y){
        parent[y]=x;
    }
    vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
        cost.assign(n,-1);
        parent.resize(n);

        for(int i=0;i<n;i++){
            parent[i]=i;
        }

        for(auto &vec:edges){
            int u=vec[0];
            int v=vec[1];
            int w=vec[2];

            int parent_u=find(u);
            int parent_v=find(v);

            if(parent_u!=parent_v){
                cost[parent_u]&=cost[parent_v];
                Union(parent_u,parent_v);
            }

            cost[parent_u]&=w;
        }

        vector<int>ans;
        for(auto &q:query){
            int s=q[0];
            int t=q[1];
            
            int p1=find(s);
            int p2=find(t);
            
            if(s==t) ans.push_back(0);
            else if(p1!=p2) ans.push_back(-1);
            else ans.push_back(cost[p1]);
        }
        return ans;
    }
};
```
# Have a Good Day 😊 UpVote?
['Array', 'Bit Manipulation', 'Union Find', 'Graph', 'C++']