|
| 1 | +const fs = require("fs"); |
| 2 | +const filePath = process.platform === "linux" ? "/dev/stdin" : "./서정우/input.txt"; |
| 3 | +const input = fs.readFileSync(filePath).toString().trim().split("\n"); |
| 4 | + |
| 5 | +const [boothes, routersCount, MAX_TIME] = input[0].split(" ").map(Number); |
| 6 | +const routers = input.slice(1).map((line) => line.split(" ").map(Number)); |
| 7 | + |
| 8 | +const times = new Set(); |
| 9 | +for (let i = 0; i < routers.length; i++) { |
| 10 | + times.add(routers[i][2]); |
| 11 | +} |
| 12 | + |
| 13 | +const timesArray = Array.from(times).sort((a, b) => a - b); |
| 14 | + |
| 15 | +class UnionFind { |
| 16 | + constructor(n) { |
| 17 | + this.parent = Array(n + 1) |
| 18 | + .fill(0) |
| 19 | + .map((_, i) => i); |
| 20 | + this.components = n; // 처음엔 모두 독립된 집합 |
| 21 | + } |
| 22 | + |
| 23 | + find(x) { |
| 24 | + if (this.parent[x] !== x) { |
| 25 | + this.parent[x] = this.find(this.parent[x]); |
| 26 | + } |
| 27 | + return this.parent[x]; |
| 28 | + } |
| 29 | + |
| 30 | + union(x, y) { |
| 31 | + const rootX = this.find(x); |
| 32 | + const rootY = this.find(y); |
| 33 | + |
| 34 | + if (rootX !== rootY) { |
| 35 | + this.parent[rootX] = rootY; |
| 36 | + this.components--; |
| 37 | + return true; |
| 38 | + } |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + getComponents() { |
| 43 | + return this.components; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +routers.sort((a, b) => a[2] - b[2]); |
| 48 | + |
| 49 | +const uf = new UnionFind(boothes); |
| 50 | +let result = 0; |
| 51 | +let currentTime = 1; |
| 52 | +let routerIndex = 0; |
| 53 | + |
| 54 | +for (const time of timesArray) { |
| 55 | + result += uf.getComponents() * (time - currentTime); |
| 56 | + |
| 57 | + while (routerIndex < routers.length && routers[routerIndex][2] === time) { |
| 58 | + const [u, v, s] = routers[routerIndex]; |
| 59 | + uf.union(u, v); |
| 60 | + routerIndex++; |
| 61 | + } |
| 62 | + |
| 63 | + currentTime = time; |
| 64 | +} |
| 65 | + |
| 66 | +result += uf.getComponents() * (MAX_TIME - currentTime + 1); |
| 67 | + |
| 68 | +console.log(result); |
0 commit comments