题目很简单,不过有些细节要注意
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000
struct edge1
{
int x,y;
int weigh;
}edge[MAX];
int father[MAX];
bool cmp(edge1 a, edge1 b)
{
return a.weigh < b.weigh;
}
void init(int n)
{
for(int i=0;i<=n;i++) //这里要注意,如果写成i<n,那么就会WA,原因是第N个数没有开辟出节点,看清题意,他是从1...N,我错了半天才找出来
{
father[i]=i;
}
}
int find_set(int x)
{
if(x==father[x]) return x;
father[x]=find_set(father[x]);
return father[x];
}
void union_set(int x,int y)
{
father[y]=x;
}
void main()
{
int N,i,a,b, sum,M;
while(cin>>N)
{
if(N==0) break;
init(N);
sum=0;
M=N*(N-1)/2;
for(i=0;i<M;i++)
{
cin>>edge[i].x>>edge[i].y>>edge[i].weigh;
}
sort(edge,edge+M,cmp);
for(i=0;i<M;i++)
{
a=find_set(edge[i].x);
b=find_set(edge[i].y);
if(a!=b)
{
union_set(a,b);
sum+=edge[i].weigh;
}
}
cout<<sum<<endl;
}
}
这样写可能有些别扭,我们干脆把数组从下标“1”开始存储
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000
struct edge1
{
int x,y;
int weigh;
}edge[MAX];
int father[MAX];
bool cmp(edge1 a, edge1 b)
{
return a.weigh < b.weigh;
}
void init(int n)
{
for(int i=1;i<=n;i++)
{
father[i]=i;
}
}
int find_set(int x)
{
if(x==father[x]) return x;
father[x]=find_set(father[x]);
return father[x];
}
void union_set(int x,int y)
{
father[y]=x;
}
void main()
{
int N,i,a,b, sum,M;
while(cin>>N)
{
if(N==0) break;
init(N);
sum=0;
M=N*(N-1)/2;
for(i=1;i<=M;i++)
{
cin>>edge[i].x>>edge[i].y>>edge[i].weigh;
}
sort(edge+1,edge+1+M,cmp);
for(i=1;i<=M;i++)
{
a=find_set(edge[i].x);
b=find_set(edge[i].y);
if(a!=b)
{
union_set(a,b);
sum+=edge[i].weigh;
}
}
cout<<sum<<endl;
}
}
下面附上用冒泡法写的算法,不过没有AC过,超时间
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000
struct edge1
{
int x,y;
int weigh;
}edge[MAX];
int father[MAX];
bool cmp(edge1 a, edge1 b)
{
return a.weigh < b.weigh;
}
void init(int n)
{
for(int i=1;i<=n;i++)
{
father[i]=i;
}
}
int find_set(int x)
{
if(x==father[x]) return x;
father[x]=find_set(father[x]);
return father[x];
}
void union_set(int x,int y)
{
father[y]=x;
}
void main()
{
int N,i,a,b, sum,M;
while(cin>>N)
{
if(N==0) break;
init(N);
sum=0;
M=N*(N-1)/2;
for(i=1;i<=M;i++)
{
cin>>edge[i].x>>edge[i].y>>edge[i].weigh;
}
sort(edge+1,edge+1+M,cmp);
for(i=1;i<=M;i++)
{
a=find_set(edge[i].x);
b=find_set(edge[i].y);
if(a!=b)
{
union_set(a,b);
sum+=edge[i].weigh;
}
}
cout<<sum<<endl;
}
}