给定无向连通加权图,编程设计求出其一棵最小生成树
/**********************************************************
[要求]:给定无向连通加权图,编程设计求出其一棵最小生成树。
**********************************************************/
#include<iostream>
using namespace std;
const int SIZE = 40;
int circuitJudge(int, int, int, int); //判断新加的边与前面的边是否构成回路
int main()
{
int i,j,n;
int a = 1;
int b;
int side[SIZE][SIZE] = { 0 }; //定义存放顶点的side(边)函数,其中二维数组
//的两个下标表示边的两个顶点,二维数组的值表示这条边的权
cout<<"输入无向连通加权图的结点数:";
cin>>n;
cout<<"若权值为0,即代表不存在这条边"<<endl;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
cout<<endl;
cout<<"边["<<i+1<<"]["<<j+1<<"]的权值为:";
cin>>side[i][j];
}
cout<<"最小生成数的编号\t起点\t终点\t权值\n";
while (1)
{
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
if (i != j)
{
if (side[i][j] == a)
{
side[j][i] = 0;
b = circuitJudge(i+1,j+1,side[i][j],n); //判断新加的边与前面的边是否构成回路
}
}
}
a++;
}
return 0;
}
int circuitJudge (int a, int b, int c, int n)
{
int i;
static int e = 0;
int d = 0,f = 0;
static int capsheaf[SIZE] = { 0 }; //用来存放图中相互可达的顶点
for (i = 0; i < n; i++)
{
if (a == capsheaf[i])
{
d = 1;
}
}
for (i = 0; i < n; i++)
{
if (b == capsheaf[i])
{
f = 1;
}
}
if (d == 1 && f == 1)
{
return 0;
}
if (d == 1)
{
for (i = 0; i < n; i++)
{
if (capsheaf[i] == 0)
{
capsheaf[i] = b;
cout<<++e<<"\t\t\t"<<a<<"\t"<<b<<"\t"<<c<<endl;
break;
}
}
}
if (f == 1)
{
for (i = 0; i < n; i++)
{
if (capsheaf[i] == 0)
{
capsheaf[i] = a;
cout<<++e<<"\t\t\t"<<a<<"\t"<<b<<"\t"<<c<<endl;
break;
}
}
}
if (d == 0 && f == 0)
{
for (i = 0; i < n; i++)
if (capsheaf[i] == 0)
{
capsheaf[i] = a;
capsheaf[i+1] = b;
cout<<++e<<"\t\t\t"<<a<<"\t"<<b<<"\t"<<c<<endl;
break;
}
}
d = 0;
f = 0;
return 0;
}