【題解】Codeforces EDU Course-2 Lesson-7-3 A. DSU with rollback

【題目敘述】http://codeforces.com/edu/course/2/lesson/7/3/practice/contest/289392/problem/A

#include <iostream>
#include <vector>
using namespace std;
 
int n, m, p[200005];
vector <vector <int> > v;
string s;
 
int f(int x){
    if (p[x] == x) return x;
    return f(p[x]);
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++){
        p[i] = i;
    }
    vector <int> tmp;
    int cnt = n;
    for (int i = 0; i < m; i++){
        cin >> s;
        if (s == "union"){
            int x, y;
            cin >> x >> y;
            x = f(x);
            y = f(y);
            if (x != y){
                if (rand()%2) swap(x, y);
                p[y] = x;
                cnt--;
                tmp.push_back(y);
            }
        }
        else if (s == "persist"){
            v.push_back(tmp);
            tmp.clear();
            continue;
        }
        else{
            for (int j:tmp){
                p[j] = j;
                cnt++;
            }
            tmp = v.back();
            v.pop_back();
        }
        cout << cnt << "\n";
    }
}
分享本文 Share with friends