|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.Comparator; |
| 3 | + |
| 4 | +public class YJ_42861 { |
| 5 | + static class Bridge { |
| 6 | + int x; |
| 7 | + int y; |
| 8 | + int cost; |
| 9 | + Bridge(int x, int y, int cost){ |
| 10 | + this.x = x; |
| 11 | + this.y = y; |
| 12 | + this.cost = cost; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + int n = 4; |
| 18 | + int[][] costs = {{0,1,1},{0,2,2},{1,2,5},{1,3,1},{2,3,8}}; |
| 19 | + System.out.println(solution(n,costs)); |
| 20 | + } |
| 21 | + |
| 22 | + static int solution(int n, int[][] costs) { |
| 23 | + int length = costs.length; |
| 24 | + Bridge[] bridgeArr = new Bridge[length]; |
| 25 | + for(int i=0; i<length; i++){ |
| 26 | + if(costs[i][2] == 0){ |
| 27 | + continue; |
| 28 | + } |
| 29 | + bridgeArr[i] = new Bridge(costs[i][0],costs[i][1],costs[i][2]); |
| 30 | + } |
| 31 | + |
| 32 | + Arrays.sort(bridgeArr, Comparator.comparingInt(o -> o.cost)); |
| 33 | + |
| 34 | + int[] parent = new int[length+1]; |
| 35 | + for(int i=1; i<length+1; i++){ |
| 36 | + parent[i] = i; |
| 37 | + } |
| 38 | + |
| 39 | + int minCost = 0; |
| 40 | + int line = 0; |
| 41 | + for(Bridge bridge : bridgeArr){ |
| 42 | + if(line == n-1){ //간선수는 n-1개 |
| 43 | + break; |
| 44 | + } |
| 45 | + |
| 46 | + if(find(parent, bridge.x) != find(parent, bridge.y)){ |
| 47 | + union(parent,bridge.x,bridge.y); |
| 48 | + minCost += bridge.cost; |
| 49 | + line++; |
| 50 | + } |
| 51 | + } |
| 52 | + return minCost; |
| 53 | + } |
| 54 | + |
| 55 | + static int find(int[] parent, int num){ |
| 56 | + if(parent[num] == num){ |
| 57 | + return parent[num]; |
| 58 | + } |
| 59 | + return parent[num] = find(parent,parent[num]); |
| 60 | + } |
| 61 | + |
| 62 | + static void union(int[] parent,int num1, int num2){ |
| 63 | + if(num1 == num2){ |
| 64 | + return; |
| 65 | + } |
| 66 | + if(num1 > num2){ |
| 67 | + parent[num1] = num2; |
| 68 | + }else{ |
| 69 | + parent[num2] = num1; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments