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.

* */node


#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;
}

ios

相關文章
相關標籤/搜索