結果

問題 No.3087 University Coloring
ユーザー GOTKAKO
提出日時 2025-04-04 21:36:01
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 84 ms / 2,000 ms
コード長 1,322 bytes
コンパイル時間 3,173 ms
コンパイル使用メモリ 209,852 KB
実行使用メモリ 7,936 KB
最終ジャッジ日時 2025-04-04 21:38:32
合計ジャッジ時間 6,751 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

class UnionFind{
    private:
    vector<int> par,siz;
    public:
    UnionFind(int N){
        par.resize(N,-1);
        siz.resize(N,1);
    }
 
    int root(int x){ //連結成分の代表頂点を返す.
        if(par.at(x) == -1) return x;
        else return par.at(x) = root(par.at(x));
    }
    bool unite(int u, int v){ //u,vを連結する 連結してた->false,した->trueを返す.
        u = root(u),v = root(v);
        if(u == v) return false;
 
        if(siz.at(u) < siz.at(v)) swap(u,v); //Union by size.
        par.at(v) = u;
        siz.at(u) += siz.at(v);
        return true;
    }
    bool issame(int u, int v){ //同じ連結成分ならtrue.
        if(root(u) == root(v)) return true;
        else return false;
    }
    int size(int pos){return siz.at(root(pos));} //posの連結成分の大きさを返す.
};

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int N,M; cin >> N >> M;
    vector<tuple<long long,int,int>> edge(M);
    for(auto &[c,a,b] : edge) cin >> a >> b >> c,a--,b--;
    sort(edge.rbegin(),edge.rend());

    long long answer = 0;
    UnionFind Z(N);
    for(auto [c,a,b] : edge){
        if(Z.issame(a,b)) continue;
        answer += 2*c; Z.unite(a,b);
    }
    cout << answer << endl;
}
0