#include <iostream> #include <vector> using namespace std; using ll = long long; vector<int> F, cnt, alias; vector<bool> got; vector<char> res; int Find(int a) { return F[a] == a ? a : F[a] = Find(F[a]); } bool Union(int a, int b) { a = Find(a); b = Find(b); F[a] = b; got[b] = got[a] || got[b]; cnt[b] += cnt[a]; return a == b; } int main() { ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); int n, q, next = 0; string ans = ""; cin >> n >> q; F.resize(n + q + 7); cnt.resize(n + q + 7); alias.resize(n + 7); res.resize(n + q + 7); got.resize(n + q + 7); for (int i = 1; i <= n; i++) { alias[i] = ++next; F[i] = i; got[i] = false; res[i] = '0'; cnt[i] = 1; } char c; for (int i = 0, a, b; i < q; i++) { cin >> c; if (c == '?') { cin >> a; a = alias[a]; if (got[Find(a)]) res[a] = '1'; else if (res[a] == '?' && cnt[Find(a)] == 1) res[a] = '0'; ans += res[a]; } else if (c == '+') { cin >> a >> b; a = alias[a]; b = alias[b]; res[a] = '?'; res[b] = '?'; if (Union(a, b)) { got[Find(a)] = true; } } else { cin >> a; cnt[Find(alias[a])]--; alias[a] = ++next; a = next; F[a] = a; got[a] = false; res[a] = '0'; cnt[a] = 1; } } cout << ans << '\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 78 79 80 81 | #include <iostream> #include <vector> using namespace std; using ll = long long; vector<int> F, cnt, alias; vector<bool> got; vector<char> res; int Find(int a) { return F[a] == a ? a : F[a] = Find(F[a]); } bool Union(int a, int b) { a = Find(a); b = Find(b); F[a] = b; got[b] = got[a] || got[b]; cnt[b] += cnt[a]; return a == b; } int main() { ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); int n, q, next = 0; string ans = ""; cin >> n >> q; F.resize(n + q + 7); cnt.resize(n + q + 7); alias.resize(n + 7); res.resize(n + q + 7); got.resize(n + q + 7); for (int i = 1; i <= n; i++) { alias[i] = ++next; F[i] = i; got[i] = false; res[i] = '0'; cnt[i] = 1; } char c; for (int i = 0, a, b; i < q; i++) { cin >> c; if (c == '?') { cin >> a; a = alias[a]; if (got[Find(a)]) res[a] = '1'; else if (res[a] == '?' && cnt[Find(a)] == 1) res[a] = '0'; ans += res[a]; } else if (c == '+') { cin >> a >> b; a = alias[a]; b = alias[b]; res[a] = '?'; res[b] = '?'; if (Union(a, b)) { got[Find(a)] = true; } } else { cin >> a; cnt[Find(alias[a])]--; alias[a] = ++next; a = next; F[a] = a; got[a] = false; res[a] = '0'; cnt[a] = 1; } } cout << ans << '\n'; return 0; } |