最小生成树
Prim+队列:
练手模板题:
https://www.luogu.com.cn/problem/P1546
AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N = 110;
int n,G[N][N],vis[N],ans;
void Prim()
{
priority_queue<pii,vector<pii>,greater<pii> > q;
q.push({0,1});
while(q.size()){
pii tmp = q.top();
q.pop();
if(vis[tmp.second]==1) continue;
vis[tmp.second]=1;
ans+=(tmp.first);
for(int i=1;i<=n;i++){
if(vis[i]==0){
q.push({G[tmp.second][i],i});
}
}
}
}
int main(){
cin >> n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
cin >> G[i][j];
}
Prim();
cout << ans;
return 0;
}
Kruskal算法:
数据结构:
priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>> q;
int fa[1001];
int get(int x)
{
if(fa[x]==0) return fa[x]=x;
return fa[x]==x?x:fa[x]=get(fa[x]);
}
void merge(int x,int y)
{
fa[get(y)]=get(x);
}
预处理:
for(int i=1;i<=m;++i)
{
int x,y,z;
cin >> x >> y >> z;
q.push({z,{x,y}});
}
核心代码:
while(q.size())
{
auto tmp=q.top();
q.pop();
int z=tmp.first,x=tmp.second.first,y=tmp.second.second;
if(get(x)!=get(y))
{
ans+=z;
n--;
merge(x,y);
}
}
//若最后n>1,则说明没有构成一个连通图;否则,构成了连通图。