TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|

Kruskal算法在实现过程中的关键和难点在于:如何判断欲加入的一条边是否与生成树中已保留的边形成回路? 我们可以将顶点划分到不同的集合中,每个集合中的顶点表示一个无回路的连通分量,很明显算法开始时,把所有n个顶点划分到n个集合中,每个集合只有一个顶点,表明顶点之间互不相通。当选取一条边时,若它的两个顶点分属于不同的集合,则表明此边连通了两个不同的连通分量,因每个连通分量无回路,所以连通后得到的连通分量仍不会产生回路,因此这条边应该保留,且把它们作为一个连通分量,即把它的两个顶点所在集合合并成一个集合。如果选取的一条边的两个顶点属于同一个集合,则此边应该舍弃,因为同一个集合中的顶点是连通无回路的,若再加入一条边则必然产生回路。
运行:
C:work>java Kruskal
spanning tree begin!Input the node number:
5
Input the graph(-1,-1,-1 to exit)
1 2 2
2 5 9
2 3 8
5 4 7
4 1 10
1 3 12
3 4 6
3 5 3
-1 -1 -1
19.0
the 1th edge:1---2
the 2th edge:3---5
the 3th edge:3---4
the 4th edge:2---3
源码下载:http://file.javaxxz.com/2014/11/30/000700343.zip |
|