-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprimsmstsub.java
71 lines (57 loc) · 1.44 KB
/
primsmstsub.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/*
* Enter your code here. Read input from STDIN. Print output to STDOUT.
* Your class should be named Solution.
*/
Scanner sc = new Scanner(System.in);
int totV = sc.nextInt();
int totE = sc.nextInt();
int distances[][] = new int[totV][totV];
boolean visited[] = new boolean[totV];
int minDistances[] = new int[totV];
for (int i = 0; i < totV; i++) {
minDistances[i] = Integer.MAX_VALUE;
for (int j = 0; j < totV; j++) {
distances[i][j] = Integer.MAX_VALUE;
}
}
for (int i = 0; i < totE; i++) {
int v1 = sc.nextInt() - 1;
int v2 = sc.nextInt() - 1;
int dist = sc.nextInt();
distances[v1][v2] = distances[v2][v1] = dist;
}
int start = sc.nextInt() - 1;
int total = 1;
int current = start;
int minDist = 0;
minDistances[current] = 0;
while (total != totV) {
visited[current] = true;
for (int i = 0; i < totV; i++) {
if (!visited[i]) {
if (minDistances[i] > distances[current][i]) {
minDistances[i] = distances[current][i];
}
}
}
minDist = Integer.MAX_VALUE;
for (int i = 0; i < totV; i++) {
if (!visited[i]) {
if (minDistances[i] < minDist) {
minDist = minDistances[i];
current = i;
}
}
}
total++;
}
minDist = 0;
for (int i = 0; i < totV; i++) {
minDist += minDistances[i];
}
System.out.println(minDist);
}
}