九度:1028<并查集>

浙大2008年研究生机试



// 畅通工程


#include <stdio.h>
#include <iostream>
#include <algorithm>

using namespace std;

int fa[110];

struct Node{
	int s;
	int e;
	int c;//cost
	int f;//flag
	bool operator < (const Node & A) const {
		return f > A.f;
	}// 已修通的路排在前面
};

bool cmp(Node x, Node y){
	return x.c < y.c;
}// 对未修的路排序,成本低在前

int Getfa(int x){
	if(x == fa[x])
		return x;
	fa[x] = Getfa(fa[x]);
	return fa[x];
}

int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("E:\\in.txt", "r", stdin);
#endif

	int n;
	while(scanf("%d", &n) && n){
		int i, nr = n*(n-1)/2 ;
		for(i=1; i<=n; i++){
			fa[i]=i;
		}

		Node buf[10000];
		for(i=0; i<nr; i++){
			scanf("%d %d %d %d", &buf[i].s, &buf[i].e, &buf[i].c, &buf[i].f);
		}

		sort(buf, buf+nr);

		for(i=0; buf[i].f == 1 && i<nr; i++){
			if(Getfa(buf[i].s) != Getfa(buf[i].e)){
				fa[Getfa(buf[i].s)] = Getfa(buf[i].e);
			}
		}// 连通已修好的路

		sort(buf+i, buf+nr, cmp);//对维修的路排序

		int ans=0;
		for(; i<nr; i++){
			if(Getfa(buf[i].s) != Getfa(buf[i].e)){
				fa[Getfa(buf[i].s)] = Getfa(buf[i].e);
				ans += buf[i].c;
			}
		}
		
		printf("%d\n", ans);

	}//while


	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值