返回题解分享
讨论 / 题解分享/ 帖子详情

最小生成树 - 题解

板子题`
#include
using namespace std;
using ll = long long;
const int N = 1e6 + 9;
struct node{
ll u,v,w;
bool operator < (const node &a) const{
if(w!=a.w) return w<a.w;
else if(v!=a.v) return v<a.v;
else return u<a.u;
}
};
ll fa[N];
ll root(int x){
return fa[x] = (fa[x] == x ? x : root(fa[x]));
}
vector<node> es;
signed main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll n,m;cin>>n>>m;
for(int i=1;i<=m;i++){
ll u,v,w;cin>>u>>v>>w;
es.push_back({u,v,w});
}
ll ans = 0;
sort(es.begin(),es.end());
for(int i=1;i<=n;i++) fa[i] = i;

for(auto &y : es){
	if(root(y.u)==root(y.v)) continue;
	ans += y.w;
	fa[root(y.v)] = root(y.u);
}


for(int i = 1; i < n; i++) if(root(i) != root(i + 1)) ans = -1;
if(ans!=-1)
cout << ans << "\n";
else cout<<"impossible";
}

0 回复 0 转发 0 喜欢 4 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!