import java.util.Scanner;
public class prim {
static class Graph{
double[][] edges;
int n;
public Graph(int n) {
this.edges = new double[n][n];
this.n = n;
}
}
public static void getPrim(Graph g,int v){
double[] lowcost=new double[g.n];
double mincost;
int[] closest=new int[g.n];
int i,j,k = 0;
for(j=0;j< g.n;j++){
lowcost[j]=g.edges[v][j];
if(lowcost[j]==0){
lowcost[j]=Integer.MAX_VALUE;
}
closest[j]=v;
}
lowcost[k]=0;
for(i=1;i< g.n;i++){
mincost=Integer.MAX_VALUE;
for(j=0;j< g.n;j++){
if(lowcost[j]!=0&&lowcost[j]<mincost){
mincost=lowcost[j];
k=j;
}
}
System.out.printf("边(%d,%d)权为:%f\n",closest[k],k,mincost);
lowcost[k]=0;
for (j=0;j< g.n;j++){
if(g.edges[k][j]!=0&&g.edges[k][j]<lowcost[j]){
lowcost[j]=g.edges[k][j];
closest[j]=k;
}
}
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int dingdian=in.nextInt();
int bian=in.nextInt();
in.nextLine();
Graph temp=new Graph(dingdian);
for(int i=0;i<bian;i++){
int qian=in.nextInt();
int hou=in.nextInt();
double value=in.nextDouble();
temp.edges[qian][hou]=value;
temp.edges[hou][qian]=value;
}
getPrim(temp,0);
}
}
结果展示:
7 9
0 5 1
0 1 6
1 2 4
1 6 3
2 3 2
3 6 5
3 4 6
4 5 8
4 6 7
边(0,5)权为:1.000000
边(0,1)权为:6.000000
边(1,6)权为:3.000000
边(1,2)权为:4.000000
边(2,3)权为:2.000000
边(3,4)权为:6.000000