最小生成树板子加例题

来自acwig ,这里只是做个个人记录

Kruskal算法求最小生成树

时间复杂度 : O(mlogm), m是边
例题

板子

#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int M = 2e5+9;
const int N = 1e5+9;
int p[N],n,m;
int Read()
{
	int s,w;
	s = 0;
	w= 1;
	char ch;
	ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch=='-') w = -1;
		ch = getchar();
	}
	while(ch>='0'&&ch<='9')
	{
		s = s*10 +ch-'0';
		ch = getchar();
	}
	return s*w;
}
struct Edge
{
	int a,b,w;
}edge[M];
//讲所有的边从小到大排序
//枚举每条边a b,和权重c
//如果说a b不连通,那么讲这条边加入集合 
bool cmp(const Edge &A, const Edge &B)
{
	return A.w<B.w; 
} 
int Find(int x)
{
	if(x!=p[x]) p[x] = Find(p[x]);
	return p[x];
}
int Kruskal()
{
	//初始化并查集 
	int res = 0,cnt = 0; 
	for(int i=1; i<=n; i++) p[i] = i;
	for(int i=1; i<=m; i++)
	{
		int x = Find(edge[i].a);
		int y = Find(edge[i].b);
		if(x!=y)//如果x y不连通 
		{
			p[x] = y;
			res+=edge[i].w;
			cnt++;
		}
    }
    if(cnt<n-1) return INF;
    return res;
}
int main() {
	
	cin>>n>>m;
	for(int i=1; i<=m; i++)
	{
	edge[i].a = Read();
	edge[i].b = Read();
	edge[i].w = Read();
	//cout<<edge[i].a<<" "<<edge[i].b<<" "<<edge[i].w<<endl;
	}
	sort(edge+1,edge+m+1,cmp);
	int t = Kruskal();
	if(t==INF) puts("impossible");
	else printf("%d",t);
	return 0;
}


朴素Prim算法求最小生成树

例题
时间复杂度 O(n^2)

板子

#include<bits/stdc++.h> 

using namespace std;
const int N = 510;
const int INF = 0x3f3f3f3f;
int g[N][N];//邻接矩阵存储图 
int dist[N];//点到集合S的将距离,初始化为正无穷 
int st[N];//判断点i是否在集合S里面 
int n,m;
int prime()
{
	memset(dist,0x3f,sizeof dist);
	int res  = 0;
	for(int i=0; i<n; i++)//总共要找n次 
	{
		int t = -1;
		for(int j=1; j<=n; j++)
		//z在1~n个节点去寻找到集合S的距离的那个节点,
		//这里的距离是指最短的 
		{
			if(!st[j]&&(t==-1||dist[t]>dist[j]))
			{
				t = j;//找到后更新t 
			} 
		} 
			if(i&&dist[t]==INF) return INF;//如果已经在找第二个点了,发现
			//没有连通,那么不可能存在最小生成树 
			if(i) res+=dist[t];
		//	cout<<i<<" "<<dist[t]<<endl;
			st[t] = true;//这个点已经加入集合S 
			for(int j=1; j<=n; j++)
			{
				dist[j] = min(dist[j],g[t][j]);
			}
	}
	return res;
}
int main()
{

	cin>>n>>m;
	memset(g,0x3f,sizeof g);
	while(m--)
	{
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		g[v][u]=g[u][v] = min(g[u][v],w); 
	}
	int t = prime();
	if(t==INF) puts("impossible");
	else printf("%d\n",t);
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值