結果

問題 No.860 買い物
ユーザー Y17
提出日時 2019-08-10 15:37:02
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 145 ms / 1,000 ms
コード長 1,051 bytes
コンパイル時間 1,425 ms
コンパイル使用メモリ 168,012 KB
実行使用メモリ 9,684 KB
最終ジャッジ日時 2024-07-19 17:08:07
合計ジャッジ時間 3,772 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 15
権限があれば一括ダウンロードができます

ソースコード

diff #

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

#define int long long

struct UnionFind{
    vector<int> tree;

    UnionFind(int n): tree(n+1, -1) {};

    int root(int i){ return tree[i] < 0 ? i : tree[i] = root(tree[i]); }

    bool unite(int i, int j){
        i = root(i), j = root(j);
        if(i == j) return false;
        tree[i] += tree[j], tree[j] = i;
        return true;
    }

    bool same(int i, int j){ return root(i) == root(j); }

    int size(int i){ return -tree[root(i)]; }
};


signed main(){
    int n;
    cin >> n;
    int ans = 0;

    int c, d;
    typedef pair<int, pair<int, int>> P;
    priority_queue<P, vector<P>, greater<P>> que;
    for(int i = 0;i < n;i++){
        cin >> c >> d;
        ans += c;
        que.push({c, {0, i+1}});
        if(i != 0) que.push({d, {i, i+1}});
    }

    UnionFind uf(n);

    while(!que.empty()){
        if(uf.unite(que.top().second.first, que.top().second.second)){
            ans += que.top().first;
        }
        que.pop();
    }

    cout << ans << endl;
    return 0;
}
0