|
| 1 | +/** |
| 2 | + * 1627. Graph Connectivity With Threshold |
| 3 | + * https://leetcode.com/problems/graph-connectivity-with-threshold/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * We have n cities labeled from 1 to n. Two different cities with labels x and y are directly |
| 7 | + * connected by a bidirectional road if and only if x and y share a common divisor strictly |
| 8 | + * greater than some threshold. More formally, cities with labels x and y have a road between |
| 9 | + * them if there exists an integer z such that all of the following are true: |
| 10 | + * - x % z == 0, |
| 11 | + * - y % z == 0, and |
| 12 | + * - z > threshold. |
| 13 | + * |
| 14 | + * Given the two integers, n and threshold, and an array of queries, you must determine for each |
| 15 | + * queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there |
| 16 | + * is some path between them). |
| 17 | + * |
| 18 | + * Return an array answer, where answer.length == queries.length and answer[i] is true if for |
| 19 | + * the ith query, there is a path between ai and bi, or answer[i] is false if there is no path. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} n |
| 24 | + * @param {number} threshold |
| 25 | + * @param {number[][]} queries |
| 26 | + * @return {boolean[]} |
| 27 | + */ |
| 28 | +var areConnected = function(n, threshold, queries) { |
| 29 | + const parent = new Array(n + 1).fill().map((_, i) => i); |
| 30 | + |
| 31 | + for (let z = threshold + 1; z <= n; z++) { |
| 32 | + for (let x = z; x <= n; x += z) { |
| 33 | + union(x, z); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return queries.map(([a, b]) => find(a) === find(b)); |
| 38 | + |
| 39 | + function find(x) { |
| 40 | + if (parent[x] !== x) { |
| 41 | + parent[x] = find(parent[x]); |
| 42 | + } |
| 43 | + return parent[x]; |
| 44 | + } |
| 45 | + |
| 46 | + function union(x, y) { |
| 47 | + parent[find(x)] = find(y); |
| 48 | + } |
| 49 | +}; |
0 commit comments