Simple Rust Solution | Union Find | Beats 100%
IntuitionWithin a connected component, any node or edge can be visited multiple times without changing the result. Therefore, the cost of walk between any two n
# Intuition

Within a connected component, any node or edge can be visited multiple times without changing the result. Therefore, the **cost of walk** between any two nodes in the same connected component is equal to the bitwise AND of all edge weights within that component. This property simplifies the computation since we only need to store one bitwise AND value per connected component.


# Approach

1. Use Union-Find to group nodes into connected components.
2. For each connected component, maintain the bitwise AND of all edge weights within that component.
3. For each query, check if the two nodes belong to the same connected component:
   - If they do, return the stored bitwise AND value for that component.
   - If they don't, return `-1`.

# Complexity

- Time complexity: $$ O((E + Q) \cdot α(n)) $$ where `α(n)` is the inverse Ackermann function). 
- Space complexity: $$ O(n) $$

# Code
```rust []
struct UnionFind {
    root: Vec<usize>,
    weight: Vec<i32>,
    size: Vec<usize>,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        Self {
            root: (0..n).collect(),
            weight: vec![i32::MAX; n],
            size: vec![1; n],
        }
    }

    fn find(&mut self, a: usize) -> usize {
        if self.root[a] == a {
            return self.root[a];
        }

        self.root[a] = self.find(self.root[a]);

        self.root[a]
    }

    fn union(&mut self, a: usize, b: usize, w: i32) {
        let a = self.find(a);
        let b = self.find(b);

        if a != b {
            let (a, b) = match self.size[a] >= self.size[b] {
                true => (a, b),
                false => (b, a),
            };

            let w = self.weight[a] & self.weight[b] & w;

            self.root[b] = a;
            self.weight[a] = w;
            self.size[a] += self.size[b];
        } else {
            self.weight[a] &= w;
        }
    }

    fn query(&mut self, a: usize, b: usize) -> i32 {
        match (self.find(a), self.find(b)) {
            (a, b) if a == b => self.weight[a],
            _ => -1,
        }
    }
}

impl Solution {
    pub fn minimum_cost(n: i32, edges: Vec<Vec<i32>>, query: Vec<Vec<i32>>) -> Vec<i32> {
        let mut uf = UnionFind::new(n as usize);

        for edge in edges {
            uf.union(edge[0] as usize, edge[1] as usize, edge[2]);
        }

        query
            .into_iter()
            .map(|q| uf.query(q[0] as usize, q[1] as usize))
            .collect()
    }
}


```
['Union Find', 'Rust']