Kruskal 算法(最小生成树)

Kruskal 算法(最小生成树)
/*
a company want to build an network of pipeline,the distance of each city is different.
the distance is as follow(i use the picture of our book,at the page of 167):
A-B:10 A-C:3 B-D:8 C-E:2 B-E:6 D-E:7 D-F:11 E-F:17
now,we want to design a project to finish the network.The cost of this project mush
lowest.

* */

191746_pZft_1759688.png


#include<iostream>
#include<cstdio>
#define n 6 //the number of the point
#define SIDE 9 //the number of the side
#define max 65536 //a very big number
using namespace std;
typedef struct edge_ edge;
struct edge_ {
int fromvex;
int endvex;
int length;
int sign;
};
edge T[SIDE];
int G[n];
/*
*Kruskal
* */
void Kruskal(int node,int e){
freopen("input.txt","r",stdin); //read from "input.txt"
int i,j=0,k,l,min,h,t=0,m;
for(i=0;i<=e-1;i++)
{
scanf("%d %d %d",&T[i].fromvex,&T[i].endvex,&T[i].length);
T[i].sign=0;
}
for(i=0;i<=node-1;i++)
G[i]=i;
while(j<node-1){
min=max;
for(i=0;i<=e-1;i++)
if( T[i].sign==0 && min>T[i].length)
{
min=T[i].length;
m=i;
}
k=T[m].fromvex;
l=T[m].endvex;
if(G[k]==G[l])
T[m].sign=2;
else {
j++;
h=G[l];
for(t=0;t<=node-1;t++)
if(G[t]==h)
G[t]=G[k];
T[m].sign=1; //use to sign the side which we select
}
}
}
/*
*use to print the Tree.
* */
void PrintTree(int node){
int i;
for(i=0;i<=node-1;i++)
if(T[i].sign==1)
printf("From %2d to %2d ,length is%4d\n",T[i].fromvex,T[i].endvex,T[i].length);
}
int main(){
Kruskal(n,SIDE);
PrintTree(SIDE);
return 0;
}

转载于:https://my.oschina.net/u/1759688/blog/308854

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值