結果

問題 No.2403 "Eight" Bridges of Königsberg
ユーザー srjywrdnprkt
提出日時 2023-08-06 02:45:18
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,832 bytes
コンパイル時間 2,039 ms
コンパイル使用メモリ 199,896 KB
最終ジャッジ日時 2025-02-15 23:40:56
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 20 WA * 11
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

struct UnionFind {
    int ngroup, N;
    vector<int> par;
    vector<int> siz;

    UnionFind(int _n) : par(_n), siz(_n), N(_n) {
        ngroup = _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]);
    }

    int unite(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        if (rx == ry) return rx;
        ngroup--;
        if (siz[rx] > siz[ry]) swap(rx, ry);
        par[rx] = ry;
        siz[ry] += siz[rx];
        return ry;
    }

    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)];
    }

    int group_count(){
        return ngroup;
    }

    vector<vector<int>> groups(){
        vector<int> rev(N);
        int nrt=0;
        for (int i=0; i<N; i++){
            if (root(i) == i){
                rev[i] = nrt;
                nrt++;
            }
        }
        vector<vector<int>> res(nrt);
        for (int i=0; i<N; i++){
            res[rev[root(i)]].push_back(i);
        }

        return res;
    }
};

int main(){
 
    int N, M, x, y;
    ll ans=0, cnt;
    cin >> N >> M;
    UnionFind tree(N+1);
    vector<int> deg(N+1);
 
    for (int i=0; i<M; i++){
        cin >> x >> y;
        tree.unite(x, y);
        deg[x]--;
        deg[y]++;
    }
    
    vector<vector<int>> g = tree.groups();
    for (auto &x : g){
        bool f=0;
        cnt = 0;
        for (auto y : x){
            if (deg[y] != 0) f=1;
            if (deg[y] > 0) cnt += deg[y];
        }
        ans += max(0LL, cnt-1) + f;
    }

    cout << ans-1 << endl;

    return 0;
}
0