-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrims.java
More file actions
80 lines (73 loc) · 2.04 KB
/
Prims.java
File metadata and controls
80 lines (73 loc) · 2.04 KB
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
72
73
74
75
76
77
78
79
80
import java.util.*;
class Node{
int id;
long w;
Node(int id,long w){
this.id = id;
this.w = w;
}
@Override
public String toString(){
return this.id+" "+this.w;
}
}
public class Prims {
static int parent[];
static long weight[];
static boolean visited[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
ArrayList<Node> arr[] = new ArrayList[V];
for(int i=0;i<V;i++) arr[i] = new ArrayList<>();
visited = new boolean[V];
parent = new int[V];
weight = new long[V];
Arrays.fill(weight, Long.MAX_VALUE);
Arrays.fill(parent,-1);
while(E--!=0){
int a = sc.nextInt(),b=sc.nextInt();
long w=sc.nextLong();
if(w <= 0) continue;
arr[a].add(new Node(b,w));
arr[b].add(new Node(a,w));
}
//System.out.println(Arrays.toString(arr));
mst(arr);
for(int i = 1; i < V; i++){
int a = i, b = parent[i] ;
long c = weight[i];
System.out.print(a>b ? b+" "+a+" " : a + " " + b+" ");
System.out.println(c);
}
}
static void mst( ArrayList<Node> arr[]){
parent[0] = -1;
weight[0] = 0;
int cur;
while(true){
cur = getMinimum(arr.length);
if(cur==-1) return;
visited[cur] = true;
for(int i=0;i<arr[cur].size();i++){
int v = arr[cur].get(i).id;
if(visited[v] == false && weight[v] > arr[cur].get(i).w){
weight[v] = arr[cur].get(i).w;
parent[v] = cur;
}
}
}
}
static int getMinimum(int V){
int res = -1;
long min = Long.MAX_VALUE;
for(int i=0;i<V;i++){
if(visited[i] == false && weight[i] < min){
min = weight[i];
res = i;
}
}
return res;
}
}