【蓝桥杯--图论】最小生成树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;
}
相关推荐
测试19986 分钟前
接口自动化测试的全面解析与实战指南
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
FPC工厂——皇榜科技1 小时前
【皇榜科技线路板质量课堂·第40篇】PPAP(生产件批准程序):批量生产前的“终极面试”
科技·面试·职场和发展·制造·pcb工艺
珂朵莉MM2 小时前
2026国信杯具身智能创新大赛-编程技能赛--本科组国赛解题报告 | 珂学家
算法·深度优先·图论
Forever Nore4 小时前
LeetCode 16 最接近的三数之和 - 双指针逼近
算法·leetcode·职场和发展
重生之后端学习4 小时前
438. 找到字符串中所有字母异位词[中等]✅
开发语言·数据结构·算法·leetcode·职场和发展
h_a_o777oah13 小时前
【图论】Tarjan 缩点:解决有向图中环的问题
c++·算法·图论·acm·强连通分量·缩点·tarjan
土司大王18 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
测试199819 小时前
Selenium 无法定位元素的几种解决方案
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
AIHR数智引擎1 天前
如何用WorkBuddy跑通HR自动化流程?
人工智能·经验分享·chatgpt·职场和发展·自动化·ai-native