//プリム法による解法 #include #include #include #include using namespace std; using ll = long long; int main(){ int N,M; cin >> N >> M; vector edge(N,vector> (0)); for(int i = 0; i < M; i++){ int a,b; ll c; cin >> a >> b >> c; a--,b--; edge[a].push_back({b,c}); edge[b].push_back({a,c}); } //チェック済み広場から1つの通路で移動可能な未チェック広場のリスト //(その通る通路の長さも情報としてもち、常にその長さで降順ソート) priority_queue> que; que.push({0,0}); vector checked(N,0);//チェック済みかどうか ll ans = 0; while(que.size()){ ll nowc,here; tie(nowc,here) = que.top(); que.pop(); if(checked[here])continue;//すでにチェック済みなら何もしない checked[here] = 1; ans += nowc; //新しくチェック済み広場が増えたので、そこから移動可能な広場を探索する for(auto j : edge[here]){ ll to,toc; tie(to,toc) = j; if(!checked[to])que.push({toc,to}); } } cout << ans * 2 << endl;//答えは最大全域木の長さの総和の2倍である点に注意 return 0; }