最小生成树
朴素版prim算法
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define int long long
typedef pair<int,int> PII;
const int N=2e5+10;
const int INF=0x3f3f3f3f3f3f3f3f;
int g[505][505];
int d[505];
int n,m;
bool st[505];
int prim()
{
memset(d,0x3f,sizeof(d));
d[1]=0;
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 ||d[t]>d[j]))
t=j;
}
if(d[t]==INF)return INF;
res+=d[t];
st[t]=true;
for(int j=1;j<=n;j++)
d[j]=min(d[j],g[t][j]);
}
return res;
}
void solve()
{
cin>>n>>m;
memset(g,0x3f,sizeof(g));
int a,b,c;
while(m--)
{
cin>>a>>b>>c;
g[a][b]=g[b][a]=min(g[a][b],c);
}
int tt=prim();
if(tt==INF)
{
cout<<"impossible"<<endl;
}
else cout<<tt<<endl;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T = 1;
//cin >> T;
while (T--)
solve();
return 0;
}
Kruskal算法
并查集+贪心
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define int long long
typedef pair<int,int> PII;
const int N=1e5+10;
const int M=2e5+10;
const int INF=0x3f3f3f3f3f3f3f3f;
int n,m;
int p[N];//并查集部分
struct node
{
int a;
int b;
int c;
bool operator < (const node &W )const
{
return c<W.c;
}
}edge[M];//存边
int find(int x)
{
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}
void solve()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
p[i]=i;
}//并查集初始化
int u,v,w;
for(int i=1;i<=m;i++)
{
cin>>u>>v>>w;
edge[i].a=u;
edge[i].b=v;
edge[i].c=w;
}//存边
sort(edge+1,edge+1+m);//排序
int cnt=0,res=0;
for(int i=1;i<=m;i++)
{
int aa=edge[i].a,bb=edge[i].b,cc=edge[i].c;
aa=find(aa);
bb=find(bb);
if(aa!=bb)//如果a,b不连通
{
p[aa]=bb;//连边a,b
res+=cc;//最小生成树权值
cnt++;//计数加了多少边
}
}
if(cnt<n-1)cout<<"impossible"<<endl;//不构成树
else cout<<res<<endl;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T = 1;
//cin >> T;
while (T--)
solve();
return 0;
}