1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <algorithm>
#include <iostream>
#include <optional>
#include <vector>

using namespace std;

int find(int u, vector<int> &us) {
    if (us[u] == u) return u;
    return us[u] = find(us[u], us);
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n, q;
    cin >> n >> q;
    vector<int> us(n);
    vector<int> mtou(n);  // the only fixed size

    vector<int> totalUSize(n);
    vector<int> realUSize(n);
    vector<bool> isUSatisfied(n);
    for (int i = 0; i < n; i++) {
        us[i] = i;
        mtou[i] = i;

        totalUSize[i] = 1;
        realUSize[i] = 1;
        isUSatisfied[i] = false;
    }

    for (int i = 0; i < q; i++) {
        char c;
        cin >> c;
        int a, b, u, u2;
        switch (c) {
            case '+':
                cin >> a >> b;
                a--;
                b--;

                u = find(mtou[a], us);
                u2 = find(mtou[b], us);
                if (u == u2) {
                    isUSatisfied[u] = true;
                    break;
                }

                if (totalUSize[u] < totalUSize[u2]) {
                    swap(u, u2);
                }

                us[u2] = u;
                totalUSize[u] += totalUSize[u2];
                realUSize[u] += realUSize[u2];
                isUSatisfied[u] = isUSatisfied[u] || isUSatisfied[u2];

                break;
            case '-':
                cin >> a;
                a--;

                u = find(mtou[a], us);
                realUSize[u]--;
                totalUSize.push_back(1);
                realUSize.push_back(1);
                isUSatisfied.push_back(false);

                mtou[a] = us.size();
                us.push_back(us.size());

                break;
            case '?':
                cin >> a;
                a--;
                u = find(mtou[a], us);
                if (isUSatisfied[u]) {
                    cout << 1;
                } else if (realUSize[u] == 1) {
                    cout << 0;
                } else {
                    cout << "?";
                }
                break;
        }
    }
}