3 顶点数n=3;接下来哪个n*(n-1)/2条道路
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
/***************************Prim********************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define Max 101
#define MM 10000000
typedef struct{
int adjtype[Max][Max];
int n;
}matrix_graph; //邻接矩阵存储图
void Create(matrix_graph *ga)//创建图
{
int i,j,v1,v2,dis,n;
scanf("%d",&ga->n);
if(ga->n==0)exit(0);
for(i=1;i<=ga->n;i++){
for(j=1;j<=ga->n;j++)
ga->adjtype[i][j]=MM;
}
n=ga->n;
for(i=1;i<=n*(n-1)/2;i++){
scanf("%d%d%d",&v1,&v2,&dis);
ga->adjtype[v1][v2]=ga->adjtype[v2][v1]=dis;
}
}
int Prim(matrix_graph garph)//用Prim算法求最小生成树
{
int i,u,j,min,Min_dis=0;
int lowdis[Max],closest[Max],set[Max];
for(i=1;i<=garph.n;i++){
lowdis[i]=MM;
set[i]=0;
// closest[i]=-1;
}
u=1;set[u]=1;
for(i=1;i<garph.n;i++){
min=MM;
for(j=1;j<=garph.n;j++){
if(garph.adjtype[u][j]<lowdis[j]){
lowdis[j]=garph.adjtype[u][j];
//closest[j]=u;
}
}
for(j=1;j<=garph.n;j++){
if(lowdis[j]<min&&!set[j]){
min=lowdis[j];
u=j;
}
}
Min_dis+=min;
set[u]=1;
}
return Min_dis;
}
int main()
{
matrix_graph graph;
int Min_dis;
while(1){
Create(&graph);
Min_dis=Prim(graph);
printf("%d\n",Min_dis);
}
return 0;
}
/******************************Dijkstra***************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define N 101
#define MAX 10000000
typedef struct{
int x,y;
int dis;
}road;
typedef struct{
road adjtype[N*(N-1)/2];
int n;
}matrix_graph;
int cmp(const void *a,const void *b)
{
return ((road *)a)->dis-((road *)b)->dis;
}
void Create(matrix_graph *ga)
{
int i,v1,v2,n,dis;
scanf("%d",&n);
if(!n)exit(0);
ga->n=n;
for(i=1;i<=n*(n-1)/2;i++){
scanf("%d%d%d",&v1,&v2,&dis);
ga->adjtype[i].x=v1;ga->adjtype[i].y=v2;
ga->adjtype[i].dis=dis;
}
}
int find(int x,int set[])
{
if(set[x]!=x)
return find(set[x],set);
return x;
}
int Dijkstra(matrix_graph ga)
{
int i,n,par1,par2,Min_dis=0;
int set[N];
n=ga.n;n=n*(n-1)/2;
for(i=1;i<=ga.n;i++)
set[i]=i;
qsort(ga.adjtype+1,n,sizeof(road),cmp);
for(i=1;i<=n;i++){
par1=find(ga.adjtype[i].x,set);
par2=find(ga.adjtype[i].y,set);
if(par1==par2)continue;
Min_dis+=ga.adjtype[i].dis;
set[par1]=par2;
}
return Min_dis;
}
int main()
{
int Min_dis;
matrix_graph graph;
while(1){
Create(&graph);
Min_dis=Dijkstra(graph);
printf("%d\n",Min_dis);
}
return 0;
}