7-50 畅通工程之局部最小花费问题 (kruskal)

输入样例:

4
1 2 1 1
1 3 4 0
1 4 1 1
2 3 3 0
2 4 2 1
3 4 5 0

输出样例:

3

代码:

 

#include<iostream>
#include<queue>
using namespace std;
const int N=110;
struct node{
	int x,y,w;
	bool operator <(const node &n1)const{
		if(w==n1.w) return x==n1.x? x>n1.x:y>n1.y;
		return w>n1.w;
	}
};
int ans;
int mp[N][N],f[N];
priority_queue<node>pq;
int fnd(int x){
	return f[x]==x?x:f[x]=fnd(f[x]);
}
int main(){
	int n; cin>>n;
	for(int i=1;i<=n;i++)
	    f[i]=i;
	for(int i=0;i<n*(n-1)/2;i++){
		int u,v,w,st;
		scanf("%d%d%d%d",&u,&v,&w,&st);
		if(st){ f[fnd(u)]=fnd(v); }
		else{
			if(fnd(u)!=fnd(v)){ pq.push({u,v,w});}
		}
	}
	while(pq.size()){
		node tmp=pq.top(); pq.pop();
		int u=tmp.x,v=tmp.y;
		if(fnd(u)!=fnd(v)){
		    ans+=tmp.w;
		    f[fnd(u)]=fnd(v);
		}
	}
	cout<<ans;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值