hdu 1879 계속 원활 한 공사

#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 * (N - 1)/2;++i){
		if(input[i].status == 1){
			//              
			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;
			}
		}
	}
	for(int i = 0; i < N*(N-1)/2;++i){
		if(input[i].status == 0){
			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("in2.txt","r",stdin);
	int N;
	while(scanf("%d",&N),N){
		for(int i = 0;i < N*(N-1)/2;++i){
			scanf("%d%d%d%d",&input[i].a,&input[i].b,&input[i].cost,&input[i].status);
		}
		memset(parent,0,sizeof(parent));
		qsort(input,N*(N-1)/2,sizeof(Edge),cmp);
		printf("%d
",kruskal(N)); } return 0; }

좋은 웹페이지 즐겨찾기