|
| 1 | +/** |
| 2 | + * @param {number} n |
| 3 | + * @param {number[][]} edges |
| 4 | + * @return {number[][]} |
| 5 | + */ |
| 6 | +const findCriticalAndPseudoCriticalEdges = function (n, edges) { |
| 7 | + const criticalEdges = [], |
| 8 | + psuedoCriticalEdges = [], |
| 9 | + map = new Map() |
| 10 | + edges.forEach((edge, i) => map.set(edge, i)) |
| 11 | + edges.sort((a, b) => a[2] - b[2]) |
| 12 | + const buildMST = (pick, skip) => { |
| 13 | + const uf = new UnionFind(n) |
| 14 | + let cost = 0 |
| 15 | + if (pick !== null) { |
| 16 | + uf.union(pick[0], pick[1]) |
| 17 | + cost += pick[2] |
| 18 | + } |
| 19 | + for (let edge of edges) { |
| 20 | + if (edge !== skip && uf.union(edge[0], edge[1])) cost += edge[2] |
| 21 | + } |
| 22 | + return uf.count === 1 ? cost : Number.MAX_SAFE_INTEGER |
| 23 | + } |
| 24 | + const minCost = buildMST(null, null) |
| 25 | + for (let edge of edges) { |
| 26 | + const index = map.get(edge) |
| 27 | + const costWithout = buildMST(null, edge) |
| 28 | + if (costWithout > minCost) { |
| 29 | + criticalEdges.push(index) |
| 30 | + } else { |
| 31 | + const costWith = buildMST(edge, null) |
| 32 | + if (costWith === minCost) psuedoCriticalEdges.push(index) |
| 33 | + } |
| 34 | + } |
| 35 | + return [criticalEdges, psuedoCriticalEdges] |
| 36 | +} |
| 37 | +class UnionFind { |
| 38 | + constructor(n) { |
| 39 | + this.parents = Array(n) |
| 40 | + .fill(0) |
| 41 | + .map((e, i) => i) |
| 42 | + this.ranks = Array(n).fill(0) |
| 43 | + this.count = n |
| 44 | + } |
| 45 | + root(x) { |
| 46 | + while (x !== this.parents[x]) { |
| 47 | + this.parents[x] = this.parents[this.parents[x]] |
| 48 | + x = this.parents[x] |
| 49 | + } |
| 50 | + return x |
| 51 | + } |
| 52 | + find(x) { |
| 53 | + return this.root(x) |
| 54 | + } |
| 55 | + union(x, y) { |
| 56 | + const [rx, ry] = [this.find(x), this.find(y)] |
| 57 | + if (this.ranks[rx] >= this.ranks[ry]) { |
| 58 | + this.parents[ry] = rx |
| 59 | + this.ranks[rx] += this.ranks[ry] |
| 60 | + } else if (this.ranks[ry] > this.ranks[rx]) { |
| 61 | + this.parents[rx] = ry |
| 62 | + this.ranks[ry] += this.ranks[rx] |
| 63 | + } |
| 64 | + if (rx !== ry) { |
| 65 | + this.count-- |
| 66 | + return true |
| 67 | + } else return false |
| 68 | + } |
| 69 | +} |
0 commit comments