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
90
91
92
93
94
95
96
97
#include "bits/stdc++.h"
using namespace std;
#define all(x) x.begin(),x.end()
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << p.first << " " << p.second; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; }
#ifdef LOCAL
#include "debug.h"
#else
#define debug(...) 42
#define ASSERT(...) 42
#endif
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> pi;
const int oo = 1e9;
struct DSU {
    vector<int> sz,parent,alive;
    vector<bool> hascycle; // if component has a cycle, set to true.
    vi active;
    DSU(int n) : sz(n,1),parent(n),alive(n,1),hascycle(n),active(n,1) {
        iota(all(parent),0);
        iota(all(active),0);
    }
    void del(int i) {
        int p = find(active[i]);
        alive[p]--;
        active[i] = sz.size();
        sz.push_back(1);
        parent.push_back(active[i]);
        hascycle.push_back(0);
        alive.push_back(1);

    }

    void link(int a, int b) {
        if(sz[a]<sz[b]) {
            swap(a,b);
        }
        sz[a]+=sz[b];
        parent[b] = a;
        hascycle[a] = hascycle[b] or hascycle[a];
        alive[a]+=alive[b];
    }
    bool unite(int a, int b) {
        a=active[a];
        b=active[b];
        int pa = find(a),pb = find(b);
        if(pa!=pb) {
            link(pa,pb);
        } else {
            pa = find(pa);
            hascycle[pa]=1;
        }
        return pa!=pb;
    }
    int find(int a) {
        if(a==parent[a]) return a;
        return parent[a] = find(parent[a]);
    }
    bool on(int i) {
        i = active[i];
        i = find(i);
        return hascycle[i];
    }
    bool off(int i) {
        i = active[i];
        i = find(i);
        return !hascycle[i] and alive[i]==1;
    }

};
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,q; cin >> n >> q;
    DSU dsu(n);
    while(q--) {
        char c; cin >> c;
        if(c=='+') {
            int a,b; cin >> a >> b;
            --a,--b;
            dsu.unite(a,b);
        } else if(c=='-') {
            int x; cin >> x;
            --x;
            dsu.del(x);
        } else if(c=='?') {
            int d; cin >> d;
            d--;
            if(dsu.on(d)) cout << '1';
            else if(dsu.off(d)) cout << '0';
            else cout << '?';
        }
    }
    cout << '\n';
}