#include <iostream> #include <vector> #include <algorithm> #include <cmath> #define st first #define nd second typedef long long ll; using namespace std; vector<int> rep, sz, cur; vector<int> old; vector<bool> all; int Find(int a) { if (rep[a] != a) rep[a] = Find(rep[a]); return rep[a]; } void Union(int a, int b) { if (sz[a] < sz[b]) swap(a, b); sz[a] += sz[b]; old[a] += old[b]; all[a] = all[a] || all[b]; rep[b] = a; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, q; cin >> n >> q; rep.resize(n+1); sz.resize(n+1); cur.resize(n+1); all.resize(n+1); old.resize(n+1); int l = n+1; for (int i = 1; i <= n; i++) { rep[i] = i; sz[i] = 1; cur[i] = i; } while (q--) { char t; cin >> t; if (t == '+') { int a, b; cin >> a >> b; a = cur[a]; b = cur[b]; int af = Find(a), bf = Find(b); if (af == bf) { all[af] = true; } else { Union(af, bf); } } if (t == '-') { int a; cin >> a; old[Find(cur[a])]++; cur[a] = l; rep.push_back(l); sz.push_back(1); old.push_back(0); all.push_back(false); l++; } if (t == '?') { int a; cin >> a; a = cur[a]; int af = Find(a); if (all[af]) cout << 1; else if (sz[af] - old[af] == 1) cout << 0; else cout << '?'; } } cout << '\n'; return 0; }
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 | #include <iostream> #include <vector> #include <algorithm> #include <cmath> #define st first #define nd second typedef long long ll; using namespace std; vector<int> rep, sz, cur; vector<int> old; vector<bool> all; int Find(int a) { if (rep[a] != a) rep[a] = Find(rep[a]); return rep[a]; } void Union(int a, int b) { if (sz[a] < sz[b]) swap(a, b); sz[a] += sz[b]; old[a] += old[b]; all[a] = all[a] || all[b]; rep[b] = a; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, q; cin >> n >> q; rep.resize(n+1); sz.resize(n+1); cur.resize(n+1); all.resize(n+1); old.resize(n+1); int l = n+1; for (int i = 1; i <= n; i++) { rep[i] = i; sz[i] = 1; cur[i] = i; } while (q--) { char t; cin >> t; if (t == '+') { int a, b; cin >> a >> b; a = cur[a]; b = cur[b]; int af = Find(a), bf = Find(b); if (af == bf) { all[af] = true; } else { Union(af, bf); } } if (t == '-') { int a; cin >> a; old[Find(cur[a])]++; cur[a] = l; rep.push_back(l); sz.push_back(1); old.push_back(0); all.push_back(false); l++; } if (t == '?') { int a; cin >> a; a = cur[a]; int af = Find(a); if (all[af]) cout << 1; else if (sz[af] - old[af] == 1) cout << 0; else cout << '?'; } } cout << '\n'; return 0; } |