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
#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using ld = long double;
using vi = vector<int>;
using vll = vector<ll>;
using vii = vector<pii>;

const int N = 3e5 + 10;
unordered_set<int> sets[N];
unordered_set<int> nieprzydzielone;
int where[N];

void gets_computer(int sx) {
  for (auto elt : sets[sx]) {
    where[elt] = -1;
  }
  sets[sx] = unordered_set<int>();
  nieprzydzielone.insert(sx);
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie();
  int n, q;

  cin >> n >> q;

  for (int i = 1; i <= n; i++) {
    where[i] = i;
    sets[i].insert(i);
  }

  for (int i = 0; i < q; i++) {
    char c;
    cin >> c;
    if (c == '?') {
      int x;
      cin >> x;
      if (where[x] == -1) {
        cout << 1;
      } else if (sets[where[x]].size() == 1) {
        cout << 0;
      } else {
        cout << "?";
      }
    } else if (c == '+') {
      int x, y;
      cin >> x >> y;

      int sx = where[x], sy = where[y];
      if (sx == sy) {
        gets_computer(sx);
      } else if (sx == -1) {
        gets_computer(sy);
      } else if (sy == -1) {
        gets_computer(sx);
      } else {
        if (sets[sx].size() < sets[sy].size()) {
          swap(sx, sy);
          swap(x, y);
        }

        sets[sx].insert(sets[sy].begin(), sets[sy].end());
        for (auto elt : sets[sy]) {
          where[elt] = sx;
        }
        sets[sy] = unordered_set<int>();
        nieprzydzielone.insert(sy);
      }
    } else if (c == '-') {
      int x;
      cin >> x;
      if (where[x] != -1) {
        sets[where[x]].erase(x);
      }
      int nowy = *nieprzydzielone.begin();
      nieprzydzielone.erase(nowy);
      where[x] = nowy;
      sets[nowy] = {x};
    }
  }

  cout << "\n";
}