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;
}
相关推荐
破刺不会编程2 分钟前
socket编程UDP
linux·运维·服务器·网络·c++·网络协议·udp
code小毛孩10 分钟前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
HalvmånEver4 小时前
在 C++ :x86(32 位)和 x64(64 位)的不同
开发语言·c++·学习
legendary_bruce6 小时前
【22-决策树】
算法·决策树·机器学习
浪成电火花6 小时前
(deepseek!)deepspeed中C++关联部分
开发语言·c++
max5006008 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
愿天堂没有C++8 小时前
剑指offer第2版——面试题4:二维数组中的查找
c++·面试
快去睡觉~10 小时前
力扣400:第N位数字
数据结构·算法·leetcode
徐归阳10 小时前
第二十四天:虚函数与纯虚函数
c++
青草地溪水旁10 小时前
UML函数原型中constraint的含义,有啥用?
c++·uml