【蓝桥杯--图论】最小生成树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;
}
相关推荐
a程序小傲1 小时前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
华清远见成都中心2 小时前
嵌入式工程师技术面试有哪些注意事项?
面试·职场和发展
沐雪架构师2 小时前
大模型Agent面试精选15题(第三辑)LangChain框架与Agent开发的高频面试题
面试·职场和发展
YoungHong19923 小时前
面试经典150题[074]:填充每个节点的下一个右侧节点指针 II(LeetCode 117)
leetcode·面试·职场和发展
元亓亓亓4 小时前
LeetCode热题100--763. 划分字母区间--中等
算法·leetcode·职场和发展
LYFlied4 小时前
【每日算法】LeetCode 70. 爬楼梯:从递归到动态规划的思维演进
算法·leetcode·面试·职场和发展·动态规划
YoungHong19924 小时前
面试经典150题[073]:从中序与后序遍历序列构造二叉树(LeetCode 106)
leetcode·面试·职场和发展
业精于勤的牙4 小时前
浅谈:算法中的斐波那契数(五)
算法·leetcode·职场和发展
regon4 小时前
第九章 述职11 交叉面试
面试·职场和发展·《打造卓越团队》
LYFlied4 小时前
【每日算法】LeetCode 105. 从前序与中序遍历序列构造二叉树
数据结构·算法·leetcode·面试·职场和发展