#3108
Hard Algorithms Minimum cost walk in weighted graph
Array Bit Manipulation Union-Find Graph Theory
68.3% acceptance
Feb 23, 2026
783
43
There is an undirected weighted graph with n vertices labeled from 0 to n - 1.
You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi.
A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.
The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator.
You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is -1.
Return the array answer, where answer[i] denotes the minimum cost of a walk for query i.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
fn find(parent: &mut Vec<usize>, mut x: usize) -> usize {
while parent[x] != x {
let pp = parent[parent[x]];
parent[x] = pp;
x = parent[x];
}
x
}
pub fn minimum_cost(n: i32, edges: Vec<Vec<i32>>, query: Vec<Vec<i32>>) -> Vec<i32> {
let n = n as usize;
let mut parent: Vec<usize> = (0..n).collect();
let mut size: Vec<usize> = vec![1; n];
// AND of all edge weights in the connected component
let mut comp_cost: Vec<i32> = vec![i32::MAX; n];
for edge in &edges {
let u = edge[0] as usize;
let v = edge[1] as usize;
let w = edge[2];
let pu = Self::find(&mut parent, u);
let pv = Self::find(&mut parent, v);
let cu = comp_cost[pu] & w;
let cv = comp_cost[pv] & w;
if pu == pv {
comp_cost[pu] = cu;
} else {
let merged = cu & cv;
if size[pu] >= size[pv] {
parent[pv] = pu;
size[pu] += size[pv];
comp_cost[pu] = merged;
} else {
parent[pu] = pv;
size[pv] += size[pu];
comp_cost[pv] = merged;
}
}
}
query
.iter()
.map(|q| {
let s = q[0] as usize;
let t = q[1] as usize;
let ps = Self::find(&mut parent, s);
let pt = Self::find(&mut parent, t);
if ps == pt {
comp_cost[ps]
} else {
-1
}
})
.collect()
}
}