最小生成树板子加例题
来自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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话