题目:
3 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 0
3 5
思路:求最小生成树问题!! 第二种方式自己写的 错误没找到! 希望指点!
#include <iostream>
#include <cstdio>#include <algorithm>
using namespace std;
const int maxn = 101;
struct Edge{
int begin;
int end;
int weight;
}edges[maxn*maxn];
int father[maxn];
int find(int a){
if(a == father[a]){
return a;
}
return father[a] = find(father[a]);
}
int kruscal(int count){
int i;
for(i = 1 ; i < maxn ; ++i){
father[i] = i;
}
int sum = 0;
for(i = 1 ; i <= count ; ++i){
int fa = find(edges[i].begin);
int fb = find(edges[i].end);
if(fa != fb){
father[fa] = fb;
sum += edges[i].weight;
}
}
return sum;
}
bool cmp(Edge a,Edge b){
return a.weight < b.weight;
}
int main(){
int n;
while(scanf("%d",&n)!=EOF,n){
int m = (n-1)*n/2;
int cnt = 1;
int i;
for(i = 1 ; i <= m ; ++i){
scanf("%d%d%d",&edges[cnt].begin,&edges[cnt].end,&edges[cnt].weight);
cnt++;
}
cnt -= 1;
sort(edges+1,edges+1+cnt,cmp);
printf("%d\n",kruscal(cnt));
}
return 0;
}
第二:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int s[100];
struct lu
{
int a1,a2,dis;
}l[5000];
int find_(int a)
{
if(a == s[a]){
return a;
}
return s[a] = find_(s[a]);
}
void find_l(int a,int b)
{
int fa=find_(a);
int fb=find_(b);
if(fa!=fb&&fa<fb)
s[b]=fa;
else if(fa!=fb&&fa>fb)
s[a]=fb;
}
bool cmp(lu a,lu b){
return a.dis < b.dis;
}
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF,n){
int sum=0,j=0;
int m=n*(n-1)/2;
for(i=0;i<100;i++)
s[i]=i;
for(i=1;i<=m;i++)
{
scanf("%d %d %d",&l[i].a1,&l[i].a2 ,&l[i].dis);
//find_l(l[i].a1,l[i].a2);
}
sort(l+1,l+i,cmp);
for(i=1;i<=m;i++)
{
if(find_(l[i].a1)!=find_(l[i].a2))
{sum+=l[i].dis;find_l(l[i].a1,l[i].a2); j++;}
if(j==n-1)
break;
}
cout << sum<< endl;
}
return 0;
}