Skip to content

3108. Minimum Cost Walk in Weighted Graph #1456

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to determine the minimum cost of a walk between two nodes in a weighted undirected graph, where the cost is defined as the bitwise AND of the weights of all edges traversed during the walk. If no such walk exists, the answer should be -1.

Approach

  1. Disjoint Set Union (DSU): First, we use DSU to identify connected components in the graph. This helps us quickly determine if two nodes are reachable from each other.
  2. Compute Component AND Values: For each connected component, compute the bitwise AND of all edge weights within that component. This value represents the minimum possible cost for any walk within the component.
  3. Query Processing: For each query, check if the start and end no…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Mar 20, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Mar 20, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
2 participants