图论---朴素Prim(稠密图)

O( n ^2 )

  • 题目通常会提示数据范围

    • V ≤ 500,两种方法均可(朴素Prim更稳)。

    • V ≤ 1e5,必须用优先队列Prim + vector 存图。

cpp 复制代码
// 最小生成树 ---朴素Prim
#include<cstring>
#include<iostream>
#include<algorithm>
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;
        //举例集合最近的点的距离是INF,说明图不连通
		if(i && dist[t]==INF) return INF;
		//只要不是第一个点,就把新加进来的这条边加到答案里
		if(i) res+=dist[t];
		//用 t 来更新其它的点
		for(int j=1;j<=n;j++) dist[j]=min(dist[j],g[t][j]);
		st[t]=true;
	}
	return res;
}
 
int main()
{
	cin>>n>>m;
	memset(g,0x3f,sizeof g);
	while(m--)
	{
		int a,b,c;
		cin>>a>>b>>c;
		g[a][b]=g[b][a]=min(g[a][b],c);
	}
	int t=prim();
	if(t==INF) puts("impossible");
	else cout<<t<<endl;
	return 0;
}
相关推荐
王老师青少年编程1 天前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程1 天前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒1 天前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣1 天前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮1 天前
Opus 4.7 来了,我并不建议你升级
算法
自我意识的多元宇宙1 天前
二叉树遍历方式代码解读(2迭代)
数据结构
leaves falling1 天前
C++模板进阶
开发语言·c++
无敌昊哥战神1 天前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__1 天前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode
再卷也是菜1 天前
算法提高篇(1)线段树(上)
数据结构·算法