結果

問題 No.2200 Weird Shortest Path
ユーザー umimel
提出日時 2023-02-11 02:25:37
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 78 ms / 2,000 ms
コード長 1,618 bytes
コンパイル時間 1,935 ms
コンパイル使用メモリ 179,160 KB
実行使用メモリ 9,472 KB
最終ジャッジ日時 2024-07-07 19:19:48
合計ジャッジ時間 7,074 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 44
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
#define drep(i, cc, n) for (ll i = (cc); i <= (n); ++i)
#define rep(i, n) drep(i, 0, n - 1)
#define all(a) (a).begin(), (a).end()
#define pb push_back
#define fi first
#define se second

const ll MOD = 1000000007;
const ll MOD2 = 998244353;
const ll INF = 1LL << 60;
const ll MAX_N = 2e5;

struct UnionFind{
    vector<ll> parent;
    vector<ll> sizes;
    
    UnionFind(ll N) : parent(N), sizes(N, 1){
        rep(i, N) parent[i] = i;
    }
    
    ll root(ll x){
        if (parent[x] == x) return x;
        return parent[x] = root(parent[x]);
    }
 
    void unite(ll x, ll y){
        ll rx = root(x);
        ll ry = root(y);
        if (rx == ry) return;
        if (sizes[rx] < sizes[ry]) swap(rx, ry);
        sizes[rx] += sizes[ry];
        parent[ry] = rx;
    }
 
    bool same(ll x, ll y){
        ll rx = root(x);
        ll ry = root(y);
        return rx == ry;
    }
 
    ll size(ll x){
        return sizes[root(x)];
    }
};

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    
    ll n, m;
    cin >> n >> m;

    vector<tuple<ll, ll, ll>> edge(m);
    rep(i, m){
        ll a, b, c;
        cin >> a >> b >> c;
        a--; b--;
        edge[i]={c, a, b};
    }

    sort(all(edge));

    UnionFind UF(n);
    ll ans = 0;
    rep(i, m){
        ll w = get<0>(edge[i]);
        ll u = get<1>(edge[i]);
        ll v = get<2>(edge[i]);

        if(!UF.same(u, v)){
            ans += w * UF.size(u)*UF.size(v);
            UF.unite(u, v);
        }
    }

    cout << ans << endl;
}
0