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
// [1A] Modernizacja Bajtocji, Kamil Debowski
#include <bits/stdc++.h>
using namespace std;
int main() {
	int n, q;
	scanf("%d%d", &n, &q);
	vector<bool> is_all(n+1);
	// Find & Union
	vector<vector<int>> inv(n+q+1);
	int next_g = n + 1;
	vector<int> g(n+1);
	vector<int> pos(n+1);
	for (int i = 1; i <= n; i++) {
		inv[i] = {i};
		g[i] = i;
		pos[i] = 0;
	}
	
	string answer;
	for (int rep = 0; rep < q; rep++) {
		char type;
		scanf(" %c", &type);
		if (type == '+') {
			int a, b;
			scanf("%d%d", &a, &b);
			assert(!(is_all[a] && is_all[b]));
			if (is_all[a] || is_all[b] || g[a] == g[b]) {
				// mark everything as is_all
				for (int x : {a, b}) {
					if (!is_all[x]) {
						for (int he : inv[g[x]]) {
							is_all[he] = true;
						}
						inv[g[x]].clear();
					}
				}
			}
			else {
				// merge small to large
				a = g[a];
				b = g[b];
				assert(a != b);
				if (inv[a].size() > inv[b].size()) {
					swap(a, b);
				}
				for (int he : inv[a]) {
					pos[he] = inv[b].size();
					g[he] = b;
					inv[b].push_back(he);
				}
				inv[a].clear();
			}
		}
		else if (type == '-') {
			int a;
			scanf("%d", &a);
			if (is_all[a]) {
				is_all[a] = false;
			}
			else {
				vector<int>& v = inv[g[a]];
				assert(v[pos[a]] == a);
				pos[v.back()] = pos[a];
				swap(v[pos[a]], v.back());
				v.pop_back();
			}
			// anyway make a new group with this 1 element
			inv[next_g] = {a};
			g[a] = next_g;
			pos[a] = 0;
			next_g++;
		}
		else if (type == '?') {
			int a;
			scanf("%d", &a);
			if (is_all[a]) {
				answer += "1";
			}
			else if ((int) inv[g[a]].size() == 1) {
				answer += "0";
			}
			else {
				answer += "?";
			}
		}
		else {
			assert(false);
		}
	}
	printf("%s\n", answer.c_str());
}