GKK 11.3 雅礼考试题

小根堆与并查集优化MST算法
本文介绍了一种使用小根堆和并查集的数据结构优化最小生成树(MST)算法的实现方法。通过优先队列高效处理边的权重,结合并查集判断连通性,实现了对Kruskal算法的有效优化。文章提供了完整的代码示例,展示了如何在竞赛编程中快速构建高效的MST求解器。

(记录一道很秒的题目,主要是记录下定义小根堆的用法)
题目链接 http://lk.yali.edu.cn/problem/22
题解 http://lk.yali.edu.cn/blogof/root/blog/25 (出题人已经说的很清楚了)

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
int n,m;
int fa[200003];
struct arr {
	int a,b;
	long long c;
};
struct cmp {
	bool operator() (arr qaq,arr qwq){
		return qaq.c>qwq.c;
	};
};
//以前不是这样写的,之前写的一种格式一直都记不住,这个好理解多了
priority_queue<arr,vector<arr>,cmp>q;
inline int read() {
	int x=0,w=1;char ch;
	while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
	if(ch=='-') w=-1,ch=getchar();
	while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+(ch-48),ch=getchar();
	return x*w;
}
int gf(int x) { return fa[x]==x?x:fa[x]=gf(fa[x]);}
int main() {
	n=read();m=read();
	while(m--) {
		int a=read(),b=read(),c=read();
		q.push((arr){a%n,b%n,c});
		q.push((arr){b%n,(a+1)%n,c+1});
	}
	for(register int i=0;i<n;++i) fa[i]=i;
	long long ans=0;
	int k=n-1;
	while(k) {
		int a=q.top().a,b=q.top().b;long long c=q.top().c;
		q.pop();
		int u=gf(a),v=gf(b);
		if(u!=v) {
			fa[u]=v;
			ans+=c;
			k--;
			if(gf((a+1)%n)!=gf((b+1)%n)) q.push((arr){(a+1)%n,(b+1)%n,c+2});
		}
	}
	cout<<ans<<endl;
	return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值