法一:prim算法,之前Wa了,后来改成kruskal算法过了,然后几天后讲过同学的提醒指导了错误的地方,
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#define N 200
#define Y 33333110
using namespace std;
int mapp[N][N],mark[N],dist[N],n,m,sum;
int prim(int v0){
memset(mark,0,sizeof(mark));
int i,j,minn,k,sum=0;
for(i=1;i<=n;i++)
dist[i]=mapp[v0][i];
mark[v0]=1; dist[v0]=0;
for(i=1;i<n;i++){
minn=Y;k=-1;
for(j=1;j<=n;j++)
if(mark[j]==0&&minn>dist[j]){
minn=dist[j];
k=j;
}
mark[k]=1;
if(k==-1){
return Y;//若没找到最小值标号,说明图不连通,要返回最大值会主函数进行判断
}
if(k!=-1){
sum+=dist[k];
for(j=1;j<=n;j++)
if(mark[j]==0&&mapp[k][j]<dist[j])
dist[j]=mapp[k][j];
}
}
return sum;
}
int main()
{
int i,j,a,b,c,y;
while(cin>>m&&m){
cin>>n;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
mapp[i][j]=Y;
for(i=1;i<=m;i++){
cin>>a>>b>>c;
if(mapp[a][b]>c)
mapp[a][b]=mapp[b][a]=c;
}
y=prim(1);
if(y==Y)//不连通时
cout<<"?"<<endl;
else
cout<<y<<endl;
}
return 0;
}
法二:kruskal算法
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#define N 200
#define Y 33333110
using namespace std;
struct node{
int a,b,c;
}mapp[N*6];
int fa[N*6];
int com(node t1,node t2){
return t1.c<t2.c;
}
int findfa(int x){
if(x!=fa[x])
fa[x]=findfa(fa[x]);
return fa[x];
}
int main()
{
int n,m,i,fx,fy,res;
while(cin>>m&&m){
cin>>n;
res=0;
for(i=1;i<=n;i++) fa[i]=i;
for(i=1;i<=m;i++)
cin>>mapp[i].a>>mapp[i].b>>mapp[i].c;
sort(mapp+1,mapp+m+1,com);
for(i=1;i<=m;i++){
fx=findfa(mapp[i].a); fy=findfa(mapp[i].b);
if(fx!=fy){
fa[fx]=fy;
res+=mapp[i].c;
--n;
}
}
if(n>1)
cout<<"?"<<endl;
else
cout<<res<<endl;
}
return 0;
}