hdu 1863 畅通工程



#include <stdio.h>
#include <stdlib.h> 
#include <string.h>

typedef struct{
	int a,b;
	int cost;
	int status; 
}Edge;

Edge input[5050];
int cost[5050];
int parent[5050];


int cmp(const void  *a,const void  *b){
	return (((Edge *)a)->cost - ((Edge *)b)->cost);
} 

int root(int n){
	if(parent[n] == 0) return n;
	else return  parent[n] = root(parent[n]);
} 

int  kruskal(int N){
	int a_root,b_root;
	int sum = 0;
	for(int i = 0; i < N;++i){
			a_root = root(input[i].a);
			b_root = root(input[i].b);
			if( a_root != b_root){
				a_root < b_root?parent[b_root] = a_root:parent[a_root] = b_root;
				sum += input[i].cost;
			}
	} 
	return sum;
}

int main(int argc, char *argv[])
{
	//FILE *fp;	
	//fp = freopen("in1.txt","r",stdin);
	int N,sum,M;
	int flag = 1;
	while(scanf("%d",&N),N){
		scanf("%d\n",&M);
		flag = 1;
		for(int i = 0;i < N;++i){
			scanf("%d%d%d",&input[i].a,&input[i].b,&input[i].cost);
		}
		memset(parent,0,sizeof(parent));
		qsort(input,N,sizeof(Edge),cmp);
		sum = kruskal(N);
		for(int i = 2; i <= M;++i){
			if(parent[i] == 0){	
				printf("?\n");
				flag = 0;
				break;
			}
		}
		if(flag)
			printf("%d\n",sum);
	}	
	return 0;
}


你可能感兴趣的:(hdu 1863 畅通工程)