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;
}
相关推荐
heimeiyingwang9 天前
【深度学习加速探秘】Winograd 卷积算法:让计算效率 “飞” 起来
人工智能·深度学习·算法
LyaJpunov9 天前
深入理解 C++ volatile 与 atomic:五大用法解析 + 六大高频考点
c++·面试·volatile·atomic
小灰灰搞电子9 天前
Qt PyQt与PySide技术-C++库的Python绑定
c++·qt·pyqt
时空自由民.9 天前
C++ 不同线程之间传值
开发语言·c++·算法
ai小鬼头9 天前
AIStarter开发者熊哥分享|低成本部署AI项目的实战经验
后端·算法·架构
小白菜3336669 天前
DAY 37 早停策略和模型权重的保存
人工智能·深度学习·算法
zeroporn9 天前
以玄幻小说方式打开深度学习词嵌入算法!! 使用Skip-gram来完成 Word2Vec 词嵌入(Embedding)
人工智能·深度学习·算法·自然语言处理·embedding·word2vec·skip-gram
Ray_19979 天前
C++二级指针的用法指向指针的指针(多级间接寻址)
开发语言·jvm·c++
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
_周游9 天前
【数据结构】_二叉树OJ第二弹(返回数组的遍历专题)
数据结构·算法