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;
}
相关推荐
kupeThinkPoem4 分钟前
哈希表有哪些算法?
数据结构·算法
小白程序员成长日记25 分钟前
2025.11.16 力扣每日一题
算法
Justinyh33 分钟前
1、CUDA 编程基础
c++·人工智能
Kuo-Teng1 小时前
LeetCode 118: Pascal‘s Triangle
java·算法·leetcode·职场和发展·动态规划
Greedy Alg1 小时前
LeetCode 32. 最长有效括号(困难)
算法
white-persist1 小时前
差异功能定位解析:C语言与C++(区别在哪里?)
java·c语言·开发语言·网络·c++·安全·信息可视化
ShineWinsu2 小时前
对于数据结构:链式二叉树的超详细保姆级解析—中
数据结构·c++·算法·面试·二叉树·校招·递归
野蛮人6号2 小时前
力扣热题100道之207课程表
算法·leetcode·职场和发展
这周也會开心2 小时前
Map的遍历方式
数据结构·算法
liu****2 小时前
20.传输层协议TCP
服务器·网络·数据结构·c++·网络协议·tcp/ip·udp