3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
3 ?
本题我犯了一个低级错误,把sort(eg,eg+n,cmp); 错写成sort(eg,eg+m,cmp);
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m;
struct stu{
int u,v,l;
};
stu eg[10000];
int h[10000];
int cmp(stu a,stu b)
{
return a.l<b.l;
}
int find(int x)
{ //int r=x;
if(x==h[x])
return x;
return h[x]=find(h[x]);
}
int join(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fy!=fx)
{
h[fx]=fy;
return 1;
}
return 0;
}
int main()
{
int i,j,k;
while(scanf("%d",&n)&&n)
{
scanf("%d",&m);
for(i=0;i<n;i++)
scanf("%d%d%d",&eg[i].u,&eg[i].v,&eg[i].l);
sort(eg,eg+n,cmp);//出现错误的地方;
if(n<m-1)//这个可以省略但是后面的不能
{//
printf("?\n");//
continue;//
}//
int w=0;
for(i=1;i<=m;i++)
h[i]=i;
int count=0;
for(i=0;i<n;i++)
{
if(join(eg[i].u,eg[i].v))
{
w+=eg[i].l;
count++;
}
}
if(count==m-1)//不可以省略,因为如果省略n大于m时也不一定能达到目的。
printf("%d\n",w);
else//
printf("?\n");//
}
return 0;
} 版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/l15738519366/article/details/47417415