結果

問題 No.1767 BLUE to RED
ユーザー srjywrdnprkt
提出日時 2023-05-28 21:12:18
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 410 ms / 2,000 ms
コード長 1,674 bytes
コンパイル時間 1,322 ms
コンパイル使用メモリ 120,072 KB
最終ジャッジ日時 2025-02-13 15:56:09
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 21
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <queue>
#include <algorithm>
#include <numeric>
#include <deque>

using namespace std;
using ll = long long;
 
struct UnionFind {
    vector<int> par;
    vector<int> siz;
 
    UnionFind(int N) : par(N), siz(N) {
        for(int i = 0; i < N; i++){
            par[i] = i;
            siz[i] = 1;
        }
    }
 
    int root(int x) {
        if (par[x] == x) return x;
        return par[x] = root(par[x]);
    }
 
    void unite(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        if (rx == ry) return;
        par[rx] = ry;
        siz[ry] += siz[rx];
    }
 
    bool same(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        return rx == ry;
    }
 
    int size(int x){
        return siz[root(x)];
    }
};

template<typename T> using pq = priority_queue<T, vector<T>, greater<T>>;
 
int main(){
 
    ll N, M, A, B, c, x, y, ans=0;
    cin >> N >> M;
    vector<pair<ll, ll>> X;
    for (int i=0; i<N; i++){
        cin >> A;
        X.push_back({A, 0});
    }
    for (int i=0; i<M; i++){
        cin >> B;
        X.push_back({B, 1});
    }
    sort(X.begin(), X.end());
    pq<tuple<ll, ll, ll>> que;
    UnionFind tree(N+M+1);


    for (int i=0; i<N+M; i++){
        if (i) que.push({X[i].first-X[i-1].first, i, i-1});
        if (X[i].second == 0) tree.unite(i, N+M);
    }

    while(!que.empty()){
        tie(c, x, y) = que.top();
        que.pop();
        if (!tree.same(x, y)){
            ans += c;
            tree.unite(x, y);
        }
    }
 
    cout << ans << endl;
 
    return 0;
}
0