我能够为某些输入运行此代码。但在某些情况下,我得到了错误的生成树。例如:如果我在执行程序时输入如下:
输入顶点数:5 输入边数:8
Enter the vertices and the weight of edge 1:
1
3
10
Enter the vertices and the weight of edge 2:
1
4
100
Enter the vertices and the weight of edge 3:
3
5
64
Enter the vertices and the weight of edge 4:
1
2
13
Enter the vertices and the weight of edge 5:
3
2
20
Enter the vertices and the weight of edge 6:
2
5
5
Enter the vertices and the weight of edge 7:
4
3
80
Enter the vertices and the weight of edge 8:
4
5
40
MINIMUM SPANNING TREE :
2-5
1-3
4-5
MINIMUM COST = 55
expected o/p :
MINIMUM SPANNING TREE :
2-5
1-3
1-2
4-5
MINIMUM COST = 68
请帮我纠正我的错误...请告诉我我在代码中所做的更改..请
代码如下:
import java.io.*;
class Edge
{
int v1,v2,wt; // wt is the weight of the edge
}
class kruskalsalgo
{
public static void main(String args[])throws IOException
{
int i,j,mincost=0;
BufferedReader br=new BufferedReader( new InputStreamReader(System.in));
System.out.println(" Enter no.of vertices:");
int v=Integer.parseInt(br.readLine());
System.out.println(" Enter no.of edges:");
int e=Integer.parseInt(br.readLine());
Edge ed[]=new Edge[e+1];
for(i=1;i<=e;i++)
{
ed[i]=new Edge();
System.out.println(" Enter the vertices and the weight of edge "+(i)+ ":");
ed[i].v1=Integer.parseInt(br.readLine());
ed[i].v2=Integer.parseInt(br.readLine());
ed[i].wt=Integer.parseInt(br.readLine());
}
for(i=1;i<=e;i++) // sorting the edges in ascending order
for(j=1;j<=e-1;j++)
{
if(ed[j].wt>ed[j+1].wt)
{
Edge t=new Edge();
t=ed[j];
ed[j]=ed[j+1];
ed[j+1]=t;
}
}
int visited[]=new int[v+1]; // array to check whether the vertex is visited or not
for(i=1;i<=v;i++)
visited[i]=0;
System.out.println("MINIMUM SPANNING TREE :");
for(i=1;i<=e;i++)
{
if(i>v)
break;
else if( visited[ed[i].v1]==0 || visited[ed[i].v2]==0)
{
System.out.println(ed[i].v1+ "-"+ ed[i].v2);
visited[ed[i].v1]=visited[ed[i].v2]=1;
mincost+=ed[i].wt;
}
}
System.out.println("MINIMUM COST = " +mincost);
}
}