最小生成树
prime算法
套板子的题
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
const int inf=0x3f3f3f3f;
typedef long long ll;
int G[maxn][maxn];
int lowcost[maxn];
bool vis[maxn];
int n,m;
int ans=0;
void prime()
{
for(int i=1;i<=n;i++)
lowcost[i]=G[1][i];
lowcost[1]=0;
vis[1]=true;
for(int i=0;i<n;i++)
{
int minn=inf;
int k=-1;
for(int j=1;j<=n;j++)
{
if(vis[j]==false&&lowcost[j]<minn)
{
k=j;
minn=lowcost[j];
}
}
if(k==-1)
break;
vis[k]=true;
lowcost[k]=0;
ans+=minn;
for(int j=1;j<=n;j++)
{
if(vis[j]==false&&lowcost[j]>G[k][j])
lowcost[j]=G[k][j];
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
memset(G,inf,sizeof(G));
memset(vis,false,sizeof(vis));
cin>>n>>m;
for(int i=0;i<m;i++)
{
int x,y,w;
cin>>x>>y>>w;
G[x][y]=min(G[x][y],w);
G[y][x]=min(G[y][x],w);
}
prime();
int flag=1;
for(int i=1;i<=n;i++)
{
if(lowcost[i]!=0)
{
flag=0;
break;
}
}
if(flag)
cout<<ans;
else
cout<<-1;
}
kruskal算法
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
const int inf=0x3f3f3f3f;
typedef long long ll;
int u[maxn],v[maxn],w[maxn],p[maxn],r[maxn];
bool cmp(int a,int b)
{
return w[a]<w[b];
}
int find(int x)
{
return p[x]==x?x:p[x]=find(p[x]);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
p[i]=i;
for(int i=1;i<=m;i++)
r[i]=i;
for(int i=1;i<=m;i++)
{
int a,b,c;
cin>>a>>b>>c;
u[i]=a;
v[i]=b;
w[i]=c;
}
sort(r+1, r + m+1,cmp);
int ans=0;
for (int i = 1; i <=m; i ++ )
{
int e=r[i];
int x=find(u[e]),y=find(v[e]);
if (x != y) // 如果两个连通块不连通,则将这两个连通块合并
{
p[x] = y;
ans += w[e];
}
}
int cnt=0;
for(int i=1;i<=n;i++)
{
if(p[i]==i)
cnt++;
}
if(cnt>1) cout<<-1;
else
cout<<ans;
}