-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1197.java
68 lines (54 loc) · 1.59 KB
/
1197.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
import java.io.*;
import java.util.*;
public class Main {
static class Edge {
int to;
int weight;
Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
private static int V, E;
private static List<Edge>[] edges;
private static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
V = Integer.parseInt(st.nextToken());
E = Integer.parseInt(st.nextToken());
edges = new List[V + 1];
for (int i = 1; i <= V; i++) {
edges[i] = new ArrayList<>();
}
for (int i = 0; i < E; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
edges[a].add(new Edge(b, c));
edges[b].add(new Edge(a, c));
}
System.out.println(prim(1));
}
private static int prim(int start) {
int totalWeight = 0;
visited = new boolean[V + 1];
PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a.weight));
pq.add(new Edge(1, 0));
while (!pq.isEmpty()) {
Edge current = pq.poll();
int node = current.to;
int weight = current.weight;
if (visited[node]) continue;
visited[node] = true;
totalWeight += weight;
for (Edge neighbor : edges[node]) {
if (!visited[neighbor.to]) {
pq.add(neighbor);
}
}
}
return totalWeight;
}
}