Scan to open on your phone
Point a camera at the QR code - it opens this exact paste, no app needed.
https://codepastes.com/zzgs8cdkbw7d6kq5kruskalC++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int INF=0x7f7f7f7f7f7f7f7f;
const int N=2e5+10;
struct NODE{
int u,v,w;
}a[N];
int n,m;
bool mycmp(const NODE &t1,const NODE &t2){
return t1.w<t2.w;
}
//DSU
int fa[N];
//fa[i]表示节点i的父亲是fa[i]
/*
fa[i]<0 表示
1. i是是根节点
2. 以i为根节点的DSU有 -fa[i] 个节点
*/
void init(int n){
for(int i=0;i<=n;i++){
fa[i]=-1;
}
}
//找到顶点x的父亲
int find(int x){
if(fa[x]<0){
return x;
}
//路径压缩
return fa[x]=find(fa[x]);
}
//将节点x和节点y合并
//合并成功,返回true
//合并不成功,返回false
bool join(int x,int y){
x=find(x);//找到x的父亲
y=find(y);//找到y的父亲
if(x==y){
//已经在同一个DSU
return false;
}
//x是y的父亲
fa[x]+=fa[y];//以x为根有几个节点
fa[y]=x;//y的父亲是x
return true;
}
/*-----DSU----*/
void solve(){
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>a[i].u>>a[i].v>>a[i].w;
}
//MST
sort(a+1,a+m+1,mycmp);
int cnt=0;//当前MST中有几条边
int ans=0;//当前MST的代价
//初始化DSU
init(n);
for(int i=1;i<=m;i++){
if(join(a[i].u,a[i].v)){
cnt++;
ans+=a[i].w;
}
}
if(cnt==n-1){
//合法答案
cout<<ans<<"\n";
} else{
//不能生成MST
cout<<"impossible\n";
}
}
void io(const string &file=""){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
if(file.size()){
string in=file+".in";
freopen(in.c_str(),"r",stdin);
string ou=file+".out";
freopen(ou.c_str(),"r",stdout);
}
}
signed main(){
io();
int T=1;
//cin>>T;
while(T--){
solve();
}
return 0;
}
1,395 chars · codepastes.com