原题代码
#include<bits/stdc++.h>usingnamespace std;constint N =200010;int n, m;int p[N];struct E{int a, b, w;booloperator<(E const&W)const{//这里return w < W.w;}}e[N];intfind(int x){if(p[x]!= x) p[x]=find(p[x]);return p[x];}intmain(){
cin >> n >> m;for(int i =0; i < m; i ++){int a, b, w;
cin >> a >> b >> w;
e[i]={a, b, w};}sort(e, e + m);for(int i =1; i < n; i ++) p[i]= i;int res =0, cnt =0;for(int i =0; i < m; i ++){int a = e[i].a, b = e[i].b, w = e[i].w;
a =find(a), b =find(b);if(a != b){
p[a]= b;
res += w;
cnt ++;}}if(cnt < n -1) cout <<"impossible";else cout << res;return0;}
具体笔记
booloperator<(E const&W)const{//这里 可以写成 bool operator < (const E & W) const{return w < W.w;}/*
*1 bool operator 是 重定义 < 时返回的类型。
*2 (E const &W) / (const E & W) 是 E中所有的元素W
*3 return w < W.w; 是 排序的标准(从小到大)
*/
建议用以下写法
struct E{int a, b, w;}e[N];//像这样将operator放到外面去,好理解…… booloperator<(E &a, E &b){return a.w < b.w;}
#include<bits/stdc++.h>usingnamespace std;constint N =200010;int n, m;int p[N];//定义数据结构E,方便对边进行操作struct E{int a, b, w;}e[N];booloperator<(E &a, E &b){return a.w < b.w;}intfind(int x){if(p[x]!= x) p[x]=find(p[x]);return p[x];}intmain(){
cin >> n >> m;for(int i =0; i < m; i ++){int a, b, w;
cin >> a >> b >> w;
e[i]={a, b, w};}sort(e, e + m);for(int i =1; i < n; i ++) p[i]= i;int res =0, cnt =0;for(int i =0; i < m; i ++){int a = e[i].a, b = e[i].b, w = e[i].w;
a =find(a), b =find(b);if(a != b){
p[a]= b;;
res += w;
cnt ++;}}if(cnt < n -1) cout <<"impossible";else cout << res;return0;}