#include <iostream> #include <vector> using namespace std; const int M = 300010; const int N = 1300010; int nextrep; int rep[M]; int leader[N]; int size_[N]; int comp[N]; int rang[N]; void init(int n,int q) { nextrep=n; for(int i = 0 ;i <= n ;i ++) { rep[i]=i; leader[i]=i; size_[i]=1; } for(int i = n ;i <=n+q ;i ++) { leader[i]=i; size_[i]=1; } } int Find(int x) { if(leader[x]!=x)leader[x]=Find(leader[x]); return leader[x]; } bool Union(int a, int b) { a=Find(a); b=Find(b); if(a==b)return false; if(rang[a]>rang[b]) { leader[b]=a; size_[a]+=size_[b]; comp[a]+=comp[b]; } else { leader[a]=b; size_[b]+=size_[a]; comp[b]+=comp[a]; } if(rang[a]==rang[b]) rang[b]++; return true; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,q; cin>>n>>q; init(n,q); for(int i = 0; i < q; i ++) { char c; int a,b; cin>>c; if(c=='+') { cin>>a>>b; a=rep[a]; b=rep[b]; Union(a,b); comp[Find(a)]++; } if(c=='-') { cin>>a; b=rep[a]; size_[Find(b)]--; comp[Find(b)]--; rep[a]=(++nextrep); } if(c=='?') { cin>>a; a=rep[a]; if(size_[Find(a)]==comp[Find(a)]) cout<<'1'; else if(comp[Find(a)]>0) cout<<'?'; else cout<<'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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | #include <iostream> #include <vector> using namespace std; const int M = 300010; const int N = 1300010; int nextrep; int rep[M]; int leader[N]; int size_[N]; int comp[N]; int rang[N]; void init(int n,int q) { nextrep=n; for(int i = 0 ;i <= n ;i ++) { rep[i]=i; leader[i]=i; size_[i]=1; } for(int i = n ;i <=n+q ;i ++) { leader[i]=i; size_[i]=1; } } int Find(int x) { if(leader[x]!=x)leader[x]=Find(leader[x]); return leader[x]; } bool Union(int a, int b) { a=Find(a); b=Find(b); if(a==b)return false; if(rang[a]>rang[b]) { leader[b]=a; size_[a]+=size_[b]; comp[a]+=comp[b]; } else { leader[a]=b; size_[b]+=size_[a]; comp[b]+=comp[a]; } if(rang[a]==rang[b]) rang[b]++; return true; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,q; cin>>n>>q; init(n,q); for(int i = 0; i < q; i ++) { char c; int a,b; cin>>c; if(c=='+') { cin>>a>>b; a=rep[a]; b=rep[b]; Union(a,b); comp[Find(a)]++; } if(c=='-') { cin>>a; b=rep[a]; size_[Find(b)]--; comp[Find(b)]--; rep[a]=(++nextrep); } if(c=='?') { cin>>a; a=rep[a]; if(size_[Find(a)]==comp[Find(a)]) cout<<'1'; else if(comp[Find(a)]>0) cout<<'?'; else cout<<'0'; } } } |