HDU 1863 并查集+最小生成树

//并查集+最小生成树,然后贴码
#include <iostream>
#include <algorithm>
using namespace std;
#define N 105
struct node{
	int from,to,w;
}edge[N];
int f[N],n,m;
int Find(int u){
	if(u==f[u])return u;
	return f[u]=Find(f[u]);
}
bool cmp(node a,node b){return a.w<b.w;}
int main(){
	while(cin>>n>>m,n){
		int i,min=1<<30;
		for(i=0;i<n;i++)
		{
			cin>>edge[i].from>>edge[i].to>>edge[i].w;
			min=min<edge[i].w?min:edge[i].w;
		}
		if(m==1 || m==2){cout<<min<<endl;continue;}
		if(n<m-1){cout<<"?"<<endl;continue;}
		sort(edge,edge+n,cmp);
		int ans=0,num=0;
		for(i=1;i<=m;i++)f[i]=i;
		for(i=0;i<n;i++)
		{
			int u=edge[i].from,v=edge[i].to;
			if(Find(u)!=Find(v))
			{
				f[v]=f[u];
				ans+=edge[i].w;
				num++;
				if(num ==m-1)break;
			}
		}
		if(num==m-1)cout<<ans<<endl;
		else cout<<"?"<<endl;
	}
	return 0;
}

你可能感兴趣的:(HDU 1863 并查集+最小生成树)