#include <bits/stdc++.h> using namespace std; const int MAX_N = 300005; const int MAX_S = 2000005; int ind[MAX_N]; int num_comp[MAX_S]; int sz[MAX_S]; vector<int> nodes[MAX_S]; int sets_cnt = 0; void init(int n){ for(int i=1;i<=n;i++){ ind[i] = sets_cnt; nodes[sets_cnt].push_back(i); sz[sets_cnt] = 1; sets_cnt++; } } void add(int a, int b){ if(ind[a] != ind[b]){ if(nodes[ind[a]].size() < nodes[ind[b]].size()) swap(a, b); num_comp[ind[a]] += num_comp[ind[b]]; int r = ind[b]; for(int u: nodes[r]){ if(ind[u] == r){ ind[u] = ind[a]; sz[ind[a]]++; nodes[ind[a]].push_back(u); } } } num_comp[ind[a]]++; // cout<<"add "<<sz[ind[a]]<<" "<<num_comp[ind[a]]<<endl; } void del(int a){ num_comp[ind[a]]--; sz[ind[a]]--; ind[a] = sets_cnt; sz[sets_cnt] = 1; nodes[sets_cnt].push_back(a); sets_cnt++; } string ans = ""; void query(int a){ // cout<<"query "<<num_comp[ind[a]]<<" "<<sz[ind[a]]<<endl; if(num_comp[ind[a]] == sz[ind[a]]){ ans += '1'; } else if(num_comp[ind[a]] == 0){ ans += '0'; } else{ ans += '?'; } } int main(){ ios_base::sync_with_stdio(0); int n, q; cin>>n>>q; init(n); for(int i=0;i<q;i++){ char type; cin>>type; if(type == '+'){ int a, b; cin>>a>>b; add(a, b); } else if(type == '-'){ int c; cin>>c; del(c); } else{ int d; cin>>d; query(d); } } cout<<ans<<endl; }
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 | #include <bits/stdc++.h> using namespace std; const int MAX_N = 300005; const int MAX_S = 2000005; int ind[MAX_N]; int num_comp[MAX_S]; int sz[MAX_S]; vector<int> nodes[MAX_S]; int sets_cnt = 0; void init(int n){ for(int i=1;i<=n;i++){ ind[i] = sets_cnt; nodes[sets_cnt].push_back(i); sz[sets_cnt] = 1; sets_cnt++; } } void add(int a, int b){ if(ind[a] != ind[b]){ if(nodes[ind[a]].size() < nodes[ind[b]].size()) swap(a, b); num_comp[ind[a]] += num_comp[ind[b]]; int r = ind[b]; for(int u: nodes[r]){ if(ind[u] == r){ ind[u] = ind[a]; sz[ind[a]]++; nodes[ind[a]].push_back(u); } } } num_comp[ind[a]]++; // cout<<"add "<<sz[ind[a]]<<" "<<num_comp[ind[a]]<<endl; } void del(int a){ num_comp[ind[a]]--; sz[ind[a]]--; ind[a] = sets_cnt; sz[sets_cnt] = 1; nodes[sets_cnt].push_back(a); sets_cnt++; } string ans = ""; void query(int a){ // cout<<"query "<<num_comp[ind[a]]<<" "<<sz[ind[a]]<<endl; if(num_comp[ind[a]] == sz[ind[a]]){ ans += '1'; } else if(num_comp[ind[a]] == 0){ ans += '0'; } else{ ans += '?'; } } int main(){ ios_base::sync_with_stdio(0); int n, q; cin>>n>>q; init(n); for(int i=0;i<q;i++){ char type; cin>>type; if(type == '+'){ int a, b; cin>>a>>b; add(a, b); } else if(type == '-'){ int c; cin>>c; del(c); } else{ int d; cin>>d; query(d); } } cout<<ans<<endl; } |