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

代码:

cpp 复制代码
#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;
}
相关推荐
liuyang-neu1 小时前
力扣中等 33.搜索旋转排序数组
java·数据结构·算法·leetcode
ganjiee00072 小时前
力扣(leetcode)每日一题 2414 最长的字母序连续子字符串的长度
java·算法·leetcode
咩咩大主教2 小时前
Linux下的简单TCP客户端和服务器
linux·服务器·c语言·开发语言·c++·tcp/ip·网络编程
ly-how2 小时前
leetcode练习 格雷编码
数据结构·算法·leetcode
阿W呀2 小时前
MATLAB-最小二乘辨识
人工智能·算法·matlab
liuyang-neu2 小时前
力扣 中等 162.寻找峰值
数据结构·算法·leetcode
scott1985122 小时前
张正友相机标定算法
数码相机·算法
临江浪怀柔ℳ2 小时前
tb的数数问题(牛客小白月赛)
算法
我只钓小鱼2 小时前
蚁群算法+A*算法寻找多目标最优路径
算法
玄【学生党】2 小时前
【c++】介绍
开发语言·c++