跳到正文

个人记录

最短路/最小生成树

EndCentury约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月9日
篇幅
约 2 分钟

版本

  1. v1当前

Prim

C++
#include<bits/stdc++.h>
using namespace std;
#define ll long long
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > que;
int head[200010],nxt[1000010],edge[1000010],ver[1000010],tot=0,dis[200010];
bool book[200010];
int n,m,cnt;
ll ans=0;
void add(int x,int y,int z)
{
	ver[++tot]=y;
	edge[tot]=z;
	nxt[tot]=head[x];
	head[x]=tot;
}
int main()
{
	scanf("%d %d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        int a,b,c;
        scanf("%d %d %d",&a,&b,&c);
        add(a,b,c),add(b,a,c);
    }
    que.push(make_pair(0,1));
    while(!que.empty()&&cnt<=n)
    {
        int u=que.top().second,v=que.top().first;
        que.pop();
        if(book[u]) continue;
        book[u]=true;
		cnt++;ans+=v;
        for(int i=head[u];i;i=nxt[i])
        	if(!book[ver[i]])
    			que.push(make_pair(edge[i],ver[i]));
    }
    printf("%lld",ans);
    return 0;
}

Kruskal

待续

Dijstra

待续

原文