結果
| 問題 | 
                            No.1390 Get together
                             | 
                    
| コンテスト | |
| ユーザー | 
                             merom686
                         | 
                    
| 提出日時 | 2021-02-12 21:58:20 | 
| 言語 | C++17  (gcc 13.3.0 + boost 1.87.0)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 48 ms / 2,000 ms | 
| コード長 | 1,083 bytes | 
| コンパイル時間 | 781 ms | 
| コンパイル使用メモリ | 92,888 KB | 
| 最終ジャッジ日時 | 2025-01-18 18:28:48 | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge2 / judge2 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 29 | 
ソースコード
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
using ll = long long;
struct UnionFind {
    UnionFind(int n) : p(n, -1) {}
    int root(int u) {
        return p[u] < 0 ? u : p[u] = root(p[u]);
    }
    int size(int u) {
        return -p[root(u)];
    }
    bool same(int u, int v) {
        return root(u) == root(v);
    }
    void unite(int u, int v) {
        u = root(u);
        v = root(v);
        if (u == v) return;
        if (p[u] > p[v]) swap(u, v);
        p[u] += p[v];
        p[v] = u;
    }
    vector<int> p;
};
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, m;
    cin >> n >> m;
    UnionFind uf(m);
    vector<int> d(n, -1);
    int r = 0;
    for (int i = 0; i < n; i++) {
        int b, c;
        cin >> b >> c;
        b--; c--;
        int t = d[c];
        d[c] = b;
        if (t < 0) continue;
        if (uf.same(t, b)) continue;
        uf.unite(t, b);
        r++;
    }
    cout << r << endl;
    return 0;
}
            
            
            
        
            
merom686