跳到正文

个人记录

Kruskal

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

文章信息

发布
2026年7月19日
收录
2026年9月2日
更新
2026年11月21日
篇幅
约 2 分钟

版本

  1. v1当前

#include <bits/stdc++.h>

using namespace std; const int N=2e5+5,mod=1e9+7; void chkmax(int &x,int y){x=max(x,y);} void chkmin(int &x,int y){x=min(x,y);} void Add(int &x,int y){x+=y,x%=mod;} int ab(int x){if(x<0)x=-x;return x;}

int read(){ int x=0,f=1;char ch=getchar(); while(ch<‘0’||ch>‘9’){if(ch==’-‘)f=-1;ch=getchar();} while(ch>=‘0’&&ch<=‘9’)x=x10+(ch-‘0’),ch=getchar(); return xf; }

int n,m; struct edge{ int u,v,w; }e[N]; int f[N];

int get(int x){ if(f[x]==x)return x; else return f[x]=get(f[x]); }

void Kruskal(){ for(int i=1;i<=n;i++)f[i]=i; int ans=0,tot=0; for(int i=1;i<=m;i++){ int u=e[i].u,v=e[i].v,fu=0,fv=0,w=e[i].w; if((fu=get(u))==(fv=get(v)))continue; f[fu]=fv,ans+=w,tot++; } if(tot==n-1)printf(“%d\n”,ans); else printf(“orz\n”); }

int main(){ n=read(),m=read(); for(int i=1;i<=m;i++){ e[i].u=read(),e[i].v=read(),e[i].w=read(); } sort(e+1,e+m+1,[&](edge x,edge y){return x.w<y.w;}); Kruskal(); return 0; }

原文