-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprims,java
More file actions
117 lines (90 loc) · 1.92 KB
/
prims,java
File metadata and controls
117 lines (90 loc) · 1.92 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import java.io.*;
import java.util.*;
class Edge
{
int dst;
int weight;
}
class Graph{
int V;
int E;
ArrayList<Edge> Edges[];
int parent[];
Edge result[];
boolean mstSet[];
int key[];
Graph(int v)
{
V=v;
Edges=new ArrayList[V];
parent=new int[V];
mstSet=new boolean[V];
result=new Edge[V];
key=new int[V];
for(int i=0;i<V;i++)
{
Edges[i]=new ArrayList<Edge>();
parent[i]=i;
mstSet[i]=false;
key[i]=Integer.MAX_VALUE;
}
key[0]=0;
parent[0]=-1;
}
void AddEdges(int a,int b,int c)
{
Edge edge=new Edge();
edge.dst=b;
edge.weight=c;
Edges[a].add(edge);
}
void PrimMst()
{
for(int i=0;i<V-1;i++)
{
int u=minkey();
mstSet[u]=true;
for(int j=0;j<Edges[u].size();j++)
{
if(mstSet[Edges[u].get(j).dst]==false && Edges[u].get(j).weight<key[Edges[u].get(j).dst])
{
parent[Edges[u].get(j).dst]=u;
key[Edges[u].get(j).dst]=Edges[u].get(j).weight;
}
}
}
}
int minkey()
{
int min=Integer.MAX_VALUE;
int index=-1;
for(int i=0;i<V;i++)
{
if(mstSet[i]==false && key[i]<min)
{
min=key[i];
index=i;
}
}
return index;
}
}
class Main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int n= scan.nextInt();
Graph graph=new Graph(n);
int e=scan.nextInt();
for(int i=0;i<e;i++)
{
graph.AddEdges(scan.nextInt(),scan.nextInt(),scan.nextInt());
}
graph.PrimMst();
for(int i=1;i<n;i++)
{
System.out.println(graph.parent[i]+"->"+i+" "+graph.key[i]);
}
}
}