【蓝桥杯--图论】最小生成树prim、kruskal


今日语录: 成功不是终点,失败不是致命,勇气才是取胜的关键。

文章目录

prim算法

cpp 复制代码
#include <cstring>
#include <algorithm>
#include <iostream>

#define _CRT_SECURE_NO_WARNINGS
using namespace std;

const int N = 510,INF = 0x3f3f3f3f;

int n, m;
int g[N][N];
int dist[N];
bool st[N];

int prim()
{
	memset(dist, 0x3f, sizeof dist);

	int res = 0;

	for (int i = 0; i < n; i++)
	{
		int t = -1;
		for (int j = 1; j <= n; j++)
			if (!st[j] && (t == -1 || dist[t] > dist[j]))
				t = j;

		if (i && dist[t] == INF)return INF;
		if (i)res += dist[t];

		for (int j = 1; j <= n; j++)dist[j] = min(dist[j], g[t][j]);

		st[t] = true;
	}
	return res;
}

int main()
{
	scanf("%d%d", &n, &m);

	memset(g, 0x3f, sizeof g);

	while (m--)
	{
		int a, b,c;
		scanf("%d%d%d", &a, &b, &c);
		g[a][b] = g[b][a] = min(g[a][b], c);
	}
	int t = prim();

	if (t == INF)puts("impossible");
	else printf("%d\n", t);

	return 0;
}

kruskal算法(稀疏图)

cpp 复制代码
#include <algorithm>
#include <iostream>

#define _CRT_SECURE_NO_WARNINGS
using namespace std;

const int N = 10010;

int n, m;
int p[N];

struct Edge
{
	int a, b, w;

	bool operator< (const Edge& W)const
	{
		return w < W.w;
	}
}edges[N];

int find(int x)
{
	if (p[x] != x)p[x] = find(p[x]);
	return p[x];
}

int main()
{
	scanf("%d%d", &n, &m);

	for (int i = 0; i < m; i++)
	{
		int a, b, w;
		scanf("%d%d%d", &a, &b, &w);
		edges[i] = { a,b,w };
	}

	sort(edges, edges + m);

	for (int i = 1; i <= n; i++)p[i] = i;

	int res = 0, cnt = 0;
	//res存储最小生成树中的权重之和
	//cnt存储的是当前存储了多少条边
	for (int i = 0; i < m; i++)
	{
		int a = edges[i].a, b = edges[i].b, w = edges[i].w;

		a = find(a), b = find(b);
		if (a != b)
		{
			p[a] = b;
			res += w;
			cnt++;
		}
	}

	if (cnt < n - 1)puts("impossible");
	else printf("%d\n", res);
	return 0;
}
相关推荐
怪兽学LLM7 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展
QQ骞7 小时前
【ECU-HIL 嵌入式车载软件测试学习路线和面试描述方式(1)】
学习·面试·职场和发展
Scabbards_8 小时前
面试Leetcode - Array
leetcode·面试·职场和发展
mm9954209 小时前
PMI三大证书:PMP、PgMP、PfMP证书对比
学习·职场和发展·项目管理·学习方法·pmp
ysa05103010 小时前
【板子】拓扑排序
c++·算法·图论·板子
罗超驿11 小时前
双指针算法详解:从入门到精通(Java版)
算法·leetcode·职场和发展
tkevinjd11 小时前
力扣300-最长递增子序列
算法·leetcode·职场和发展·动态规划·贪心
aqiu11111114 小时前
【算法日记20】LeetCode 438. 找到所有字母异位词:定长滑动窗口的极致优雅
算法·leetcode·职场和发展
tkevinjd14 小时前
416分割等和子集
java·python·算法·leetcode·职场和发展
我命由我123451 天前
复利极简理解
经验分享·笔记·学习·职场和发展·求职招聘·职场发展·学习方法