链接:http://acm.hdu.edu.cn/showproblem.php?pid=1863
分析:裸的kruskal
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<bitset>
using namespace std;
struct Edge
{
int start,end,length;
bool visit;
}edge[110000];
int cmp(Edge a,Edge b)
{
return a.length<b.length;
}
int father[1100];
int n,m;
int num;
int find(int x)
{
if (father[x]==x) return x;
father[x]=find(father[x]);
return father[x];
}
bool Union(int x,int y)
{
int f1=find(x);
int f2=find(y);
if (f1==f2) return false;
num++;
if (f1<f2) father[f1]=f2;
else father[f2]=f1;
return true;
}
int kruskal(int n,int m)
{
int i,j=0;
int sum=0;
for (i=0;i<n;i++) father[i]=i;
sort(edge,edge+m,cmp);
for (i=0;i<m&&j<n;i++)
{
if (Union(edge[i].start,edge[i].end))
{
sum+=edge[i].length;
edge[i].visit=1;
j++;
}
}
return sum;
}
int main()
{
while (scanf("%d %d",&m,&n)==2&&m)
{
num=0;
for (int i=0;i<m;i++)
{
scanf("%d %d %d",&edge[i].start,&edge[i].end,&edge[i].length);
edge[i].visit=false;
}
int ans=kruskal(n,m);
if (num!=n-1) printf("?\n");
else printf("%d\n",ans);
}
return 0;
}