|
| 1 | +/** |
| 2 | + * 3108. Minimum Cost Walk in Weighted Graph |
| 3 | + * https://leetcode.com/problems/minimum-cost-walk-in-weighted-graph/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is an undirected weighted graph with n vertices labeled from 0 to n - 1. |
| 7 | + * |
| 8 | + * You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that |
| 9 | + * there is an edge between vertices ui and vi with a weight of wi. |
| 10 | + * |
| 11 | + * A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, |
| 12 | + * and each edge connects the vertex that comes before it and the vertex that comes after it. |
| 13 | + * It's important to note that a walk may visit the same edge or vertex more than once. |
| 14 | + * |
| 15 | + * The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the |
| 16 | + * weights of the edges traversed during the walk. In other words, if the sequence of edge weights |
| 17 | + * encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 |
| 18 | + * & ... & wk, where & denotes the bitwise AND operator. |
| 19 | + * |
| 20 | + * You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find |
| 21 | + * the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no |
| 22 | + * such walk, the answer is -1. |
| 23 | + * |
| 24 | + * Return the array answer, where answer[i] denotes the minimum cost of a walk for query i. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number} n |
| 29 | + * @param {number[][]} edges |
| 30 | + * @param {number[][]} query |
| 31 | + * @return {number[]} |
| 32 | + */ |
| 33 | +var minimumCost = function(n, edges, query) { |
| 34 | + const parent = new Array(n).fill().map((_, i) => i); |
| 35 | + const costs = new Array(n).fill(2 ** 17 - 1); |
| 36 | + |
| 37 | + for (const [u, v, w] of edges) { |
| 38 | + const [p1, p2] = [find(u), find(v)]; |
| 39 | + parent[p1] = p2; |
| 40 | + costs[p1] = costs[p2] = costs[p1] & costs[p2] & w; |
| 41 | + } |
| 42 | + |
| 43 | + for (let i = 0; i < n; i++) { |
| 44 | + parent[i] = find(i); |
| 45 | + } |
| 46 | + |
| 47 | + return query.map(([s, t]) => { |
| 48 | + if (s === t) return 0; |
| 49 | + return parent[s] === parent[t] ? costs[parent[s]] : -1; |
| 50 | + }); |
| 51 | + |
| 52 | + function find(key) { |
| 53 | + if (parent[key] !== key) { |
| 54 | + parent[key] = find(parent[key]); |
| 55 | + } |
| 56 | + return parent[key]; |
| 57 | + } |
| 58 | +}; |
0 commit comments