秋天的小溪123 @ 2023-05-14 00:53:34
//Kruskal
#include<bits/stdc++.h>
using namespace std;
int n,m,fa[5000],ans,cnt;
struct aaaa{
int u,v,w;
}f[200000];
bool cmp(aaaa a,aaaa b)
{
return a.w<b.w;
}
int find(int x)
{
while(x!=fa[x]) x=fa[x]=fa[fa[x]];
return x;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=m;i++)
cin>>f[i].u>>f[i].v>>f[i].w;
sort(f+1,f+m+1,cmp);
int cnt=0;
for(int i=1;i<=m;i++)
{
int eu,ev;
eu=find(f[i].u);
ev=find(f[i].v);
if(eu==ev) continue;
ans+=f[i].w;
fa[eu]=ev;
cnt++;
if(cnt==n-1) break;
}
cout<<ans;
return 0;
}
by Loic_ @ 2023-05-14 00:56:09
并查集不是这么写的。。吧?
by HeCao2008 @ 2023-05-14 02:45:28
并查集写错了,常用模板是:
int find(int x){
if(fa[x]==x)return x;
else return fa[x]=find(fa[x]);
}
by ForgotDream_CHN @ 2023-05-14 07:31:37
@HeCao2008 并查集没错,这是非递归的并查集写法
by ForgotDream_CHN @ 2023-05-14 07:31:51
jiangly 就是这么写的
by ForgotDream_CHN @ 2023-05-14 07:32:32
@秋天的小溪123 数组开小了
by ForgotDream_CHN @ 2023-05-14 07:33:55
还有,不连通的时候要特判
by HeCao2008 @ 2023-05-14 07:43:56
@ForgotDream_CHN ???前一天晚上我脑子出问题了,确实没错,我也不知道我为什么认为这是错的
by 秋天的小溪123 @ 2023-05-14 12:17:27
oh,谢谢