#include <stdio.h>
#include <stdlib.h>
void adjmatrix(int a[][6],int n){//创建带权图邻接矩阵
int i,j,k,weight;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=100;
for(i=0;i<n;i++)
{
scanf("%d%d",&j,&weight);
while(j!=-1){
a[i][j]=weight;
scanf("%d%d",&j,&weight);
}
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(i==j)
a[i][j]=0;
printf("%d\t",a[i][j]);
if(j==n-1&&i!=n-1)
printf("\n");
}
}
typedef struct cell{
int lowcost;
int vex;
}cell;
cell closedge[20];
typedef struct tree{
int head;
int tail;
int cost;
}tree;
tree TE[20];//生成树的节点
void Prim(int n,int edge[][6]){//prim生成最小支撑树
int i=0;
int count;
for(i=0;i<n;i++)//以1为顶点初始化数组closedge
{closedge[i].lowcost=edge[0][i];
closedge[i].vex=0;
}
closedge[0].vex=-1;//顶点1进入集合u
count=0;//支撑树的边计数器count
int min,v,j;
for(i=0;i<n-1;i++){//循环n-1次//构造图的最小支撑树
min=100;//设置最小值min
v=0;
for(j=0;j<n;j++)//求当前权值最小的边和该边的终点v
{
if(closedge[j].vex!=-1&&closedge[j].lowcost<min){
v=j;
min=closedge[j].lowcost;
}
}
if(v!=0){
TE[count].head=closedge[v].vex;
TE[count].tail=v;
TE[count].cost=closedge[v].lowcost;
count++;
closedge[v].lowcost=0;
closedge[v].vex=-1;//顶点v进入集合u
for(j=0;j<n;j++)//因为v进入u中,某些顶点的相应的值要进行修改
if(closedge[j].vex!=-1&&edge[v][j]<closedge[j].lowcost)
{
closedge[j].lowcost=edge[v][j];
closedge[j].vex=v;
}
}
}
}
/*0 1 1
0 2 1
0 3 1
1 3 1
2 3 1*///无权图邻接矩阵测试数据(课本图6.6)
int main()
{ int n=6;
int a[6][6];
adjmatrix(a,n);
Prim(n,a);
int i=0;
printf("\n");
for(i=0;i<n;i++){
//if(i==0){ i++;
//printf("%d\t%d\t",TE[i].head,TE[i].tail);}
//else
printf("%d\t",TE[i].head);
}
return 0;
}
/*1 1
2 4
3 7
-1 0
0 1
2 4
4 2
-1 0
0 4
1 4
3 2
4 5
5 3
-1 0
0 7
2 2
5 6
-1 0
1 2
2 5
5 3
-1 0
2 3
3 6
4 3
-1 0*/