|
| 1 | +class UnionFind { |
| 2 | + constructor() { |
| 3 | + this.sizes = new Map() |
| 4 | + this.parents = new Map() |
| 5 | + } |
| 6 | + |
| 7 | + find(x){ |
| 8 | + if (x !== (this.parents.get(x) ?? x)) { |
| 9 | + this.parents.set(x, this.find(this.parents.get(x) ?? x)); |
| 10 | + } |
| 11 | + return this.parents.get(x) ?? x; |
| 12 | + } |
| 13 | + size(x) { |
| 14 | + return (this.sizes.get(this.find(x)) ?? 1); |
| 15 | + } |
| 16 | + connected(p, q) { |
| 17 | + return this.find(p) == this.find(q); |
| 18 | + } |
| 19 | + union(a, b) { |
| 20 | + const fa = this.find(a); |
| 21 | + const fb = this.find(b); |
| 22 | + if (fa == fb) { |
| 23 | + return; |
| 24 | + } |
| 25 | + const sa = this.sizes.get(fa) ?? 1; |
| 26 | + const sb = this.sizes.get(fb) ?? 1; |
| 27 | + |
| 28 | + if (sa < sb) { |
| 29 | + this.parents.set(fa, fb); |
| 30 | + this.sizes.set(fb, sb + sa); |
| 31 | + } else { |
| 32 | + this.parents.set(fb, fa); |
| 33 | + this.sizes.set(fa, sb + sa); |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | +/** |
| 38 | + * @param {number} n |
| 39 | + * @param {number[][]} roads |
| 40 | + * @return {number} |
| 41 | + */ |
| 42 | +var minScore = function(n, roads) { |
| 43 | + const uf = new UnionFind(); |
| 44 | + |
| 45 | + for (const [a, b] of roads) { |
| 46 | + uf.union(a, b); |
| 47 | + } |
| 48 | + let ans = Infinity; |
| 49 | + |
| 50 | + for (const [i, j, d] of roads) { |
| 51 | + if (uf.connected(1, i) && uf.connected(1, j)) { |
| 52 | + ans = Math.min(ans, d); |
| 53 | + } |
| 54 | + } |
| 55 | + return ans; |
| 56 | +}; |
0 commit comments