Official
D - 離島を結ぶ橋 / Bridges Connecting Remote Islands Editorial
by
D - 離島を結ぶ橋 / Bridges Connecting Remote Islands Editorial
by
physics0523
この問題は、 最小全域木問題 そのものです。
- グラフアルゴリズムの基礎を学ぶー最小全域木
- うさぎでもわかる離散数学(グラフ理論) 第13羽 最小全域木の求め方(クラスカル法・プリム法)
- 最小全域木(クラスカル法とUnionFind)
- クラスカル法による最小全域木を求めるアルゴリズム
単体では DSU(UnionFind) を用いることで実装が楽になるクラスカル法が好まれる傾向にありますが、問題によってはプリム法やその考え方が問われる場合もあるので、両方を学習することが望ましいです。
実装例では、クラスカル法を用いています。
実装例 (C++):
#include<bits/stdc++.h>
#include<atcoder/dsu>
using namespace std;
using namespace atcoder;
using ll=long long;
int main(){
ll N,M;
cin >> N >> M;
vector<array<ll,3>> edge(M);
for(ll i=0;i<M;i++){
cin >> edge[i][1] >> edge[i][2] >> edge[i][0];
}
sort(edge.begin(),edge.end());
dsu d(N+1);
ll res=0;
for(auto [w,u,v] : edge){
if(!d.same(u,v)){
res+=w;
d.merge(u,v);
}
}
if(d.size(1)!=N){res=-1;}
cout << res << "\n";
return 0;
}
posted:
last update:
