3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
3 ?
明显的克鲁斯卡尔啊,按权值排序然后并查集开始合并,最后判断是否连通就可以了。
#include <cstdio> #include <cstdlib> #include <algorithm> using namespace std; const int maxx = 102; typedef struct Road{ int x; int y; int cost; }Road; int pre[maxx],cnt,res; Road road[maxx*maxx+1]; void init(int n){ int i; for(i=1;i<=n;++i){ pre[i]=i; } } int root(int x){ if(x!=pre[x]){ pre[x] = root(pre[x]); } return pre[x]; } int merge(int x,int y){ int fa = root(x); int fb = root(y); int ret = 0; if(fa!=fb){ --cnt; pre[fa] = fb; ret = 1; } return ret; } int cmp(const void *a,const void *b){ Road *pa = (Road *)a; Road *pb = (Road *)b; return pa->cost-pb->cost; } int main(){ int n,m,i,flg; while(scanf("%d %d",&n,&m) && n!=0){ init(m); cnt = m-1; res = 0; for(i=0;i<n;++i){ scanf("%d %d %d",&road[i].x,&road[i].y,&road[i].cost); } qsort(road,n,sizeof(Road),cmp); for(i=0;i<n;++i){ flg = merge(road[i].x,road[i].y); if(flg==1){ res += road[i].cost; } } if(cnt!=0){ printf("?\n"); }else{ printf("%d\n",res); } } return 0; }
杭电ACM HDU 1863 杭电ACM HDU 1863 杭电ACM HDU 1863 杭电ACM HDU 1863
原文链接:http://blog.csdn.net/iaccepted/article/details/20567989 作者:csdn 凌风