forked from nanwan03/poj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1258 Agri-Net.java
57 lines (56 loc) · 1.51 KB
/
1258 Agri-Net.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while ((input = in.readLine()) != null) {
if (input.equals("")) {
break;
}
int size = Integer.parseInt(input);
int[][] map = new int[size][size];
int temp = size;
while (temp-- > 0) {
int index = 0;
while (index != size) {
String[] strs = in.readLine().split(" ");
for (int i = 0; i < strs.length; i++, index++) {
map[size - temp - 1][index] = Integer.parseInt(strs[i]);
}
}
}
System.out.println(prim(map, size));
}
}
private static int prim(int[][] map, int size) {
int sum = 0;
int[] lowCost = new int[size];
boolean[] used = new boolean[size];
for (int i = 0; i < size; ++i) {
lowCost[i] = map[0][i];
used[i] = false;
}
used[0] = true;
for (int i = 1; i < size; ++i) {
int j = 0;
while (used[j]) {
j++;
}
for (int k = 0; k < size; ++k) {
if ((!used[k]) && (lowCost[k] < lowCost[j])) {
j = k;
}
}
sum += lowCost[j];
used[j] = true;
for (int k = 0; k < size; ++k) {
if (!used[k] && (map[j][k] < lowCost[k])) {
lowCost[k] = map[j][k];
}
}
}
return sum;
}
}