Skip to content

Commit 55b2dcc

Browse files
authored
[백준 2406] 안정적인 네트워크 - MST
1 parent cc675fc commit 55b2dcc

File tree

1 file changed

+114
-0
lines changed

1 file changed

+114
-0
lines changed

hoseok/week80/Boj2406.java

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
class Main {
5+
6+
static class Edge implements Comparable<Edge> {
7+
int a, b, cost;
8+
9+
public Edge(int a, int b, int cost) {
10+
this.a = a;
11+
this.b = b;
12+
this.cost = cost;
13+
}
14+
15+
@Override
16+
public int compareTo(Edge e) {
17+
return cost - e.cost;
18+
}
19+
}
20+
21+
static int n, m;
22+
static Edge[] edges;
23+
static PriorityQueue<Edge> pq = new PriorityQueue<>();
24+
static int[] parents;
25+
26+
public static void main(String[] args) throws Exception {
27+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
28+
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
29+
StringTokenizer st = new StringTokenizer(br.readLine());
30+
n = Integer.parseInt(st.nextToken());
31+
m = Integer.parseInt(st.nextToken());
32+
edges = new Edge[(n - 1) * n / 2];
33+
parents = new int[n + 1];
34+
35+
for (int i = 0; i <= n; i++) {
36+
parents[i] = i;
37+
}
38+
39+
int uniqueCount = 0;
40+
for (int i = 0; i < m; i++) {
41+
st = new StringTokenizer(br.readLine());
42+
int a = Integer.parseInt(st.nextToken());
43+
int b = Integer.parseInt(st.nextToken());
44+
45+
if (union(a, b)) {
46+
uniqueCount++;
47+
}
48+
}
49+
50+
int index = 0;
51+
for (int i = 0; i < n; i++) {
52+
st = new StringTokenizer(br.readLine());
53+
for (int j = 0; j < n; j++) {
54+
int cost = Integer.parseInt(st.nextToken());
55+
if (i <= j) {
56+
continue;
57+
}
58+
edges[index] = new Edge(i + 1, j + 1, cost);
59+
pq.offer(edges[index++]);
60+
}
61+
}
62+
63+
index = 0;
64+
Edge[] usedEdges = new Edge[n - 2 - uniqueCount];
65+
int count = uniqueCount;
66+
int sum = 0;
67+
68+
while (!pq.isEmpty() && count < n - 2) {
69+
Edge edge = pq.poll();
70+
71+
if (edge.a == 1 || edge.b == 1) {
72+
continue;
73+
}
74+
if (union(edge.a, edge.b)) {
75+
count++;
76+
sum += edge.cost;
77+
usedEdges[index++] = edge;
78+
}
79+
}
80+
StringBuilder answer = new StringBuilder();
81+
answer.append(sum).append(" ").append(n - 2 - uniqueCount).append("\n");
82+
83+
for (Edge edge : usedEdges) {
84+
answer.append(edge.a).append(" ").append(edge.b).append("\n");
85+
}
86+
87+
bw.write(answer.toString());
88+
bw.flush();
89+
bw.close();
90+
}
91+
92+
public static boolean union(int a, int b) {
93+
a = find(a);
94+
b = find(b);
95+
96+
if (a == b) {
97+
return false;
98+
}
99+
if (a > b) {
100+
parents[a] = b;
101+
} else {
102+
parents[b] = a;
103+
}
104+
return true;
105+
}
106+
107+
public static int find(int a) {
108+
if (a == parents[a]) {
109+
return a;
110+
}
111+
112+
return parents[a] = find(parents[a]);
113+
}
114+
}

0 commit comments

Comments
 (0)