#include <bits/stdc++.h> using namespace std; int n,q,a,b; char c; vector <char> stan; vector <int> p; vector <int> r; vector <int> k; vector <int> rt; vector <int> t; vector <int> v[2500005]; queue <int> frid; int nev(int x) { if(frid.empty()) { p.push_back(-1); r.push_back(0); k.push_back(0); rt.push_back(x); return p.size()-1; } else { int y=frid.front(); frid.pop(); rt[y]=x; return y; } } void fri(int x) { if(t[rt[x]]!=x)frid.push(x); p[x]=-1; r[x]=0; k[x]=0; if(t[rt[x]]==x&&stan[rt[x]]=='?')stan[rt[x]]='1'; for(int i=0;i<(int)v[x].size();i++) { int neo=v[x][i]; if(p[neo]!=-1)fri(neo); } v[x].clear(); return; } int fin(int x) { if(p[x]==-1)return x; p[x]=fin(p[x]); return p[x]; } void uni(int x,int y) { x=fin(x); y=fin(y); if(x==y) { fri(x); } else { v[x].push_back(y); v[y].push_back(x); if(r[x]>=r[y]) { p[y]=x; k[x]+=k[y]+1; if(r[x]==r[y])r[x]++; } else if(r[x]<r[y]) { p[x]=y; k[y]+=k[x]+1; } } return; } int main() { std::ios_base::sync_with_stdio(0); cin>>n>>q; t.resize(n+3,0); stan.resize(n+3,'0'); for(int i=1;i<=n;i++)t[i]=nev(i); for(int i=0;i<q;i++) { cin>>c; if(c=='+') { cin>>a>>b; stan[a]='?'; stan[b]='?'; uni(t[a],t[b]); } else if(c=='-') { cin>>a; stan[a]='0'; t[a]=nev(a); } else if(c=='?') { cin>>a; cout<<stan[a]; } } 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | #include <bits/stdc++.h> using namespace std; int n,q,a,b; char c; vector <char> stan; vector <int> p; vector <int> r; vector <int> k; vector <int> rt; vector <int> t; vector <int> v[2500005]; queue <int> frid; int nev(int x) { if(frid.empty()) { p.push_back(-1); r.push_back(0); k.push_back(0); rt.push_back(x); return p.size()-1; } else { int y=frid.front(); frid.pop(); rt[y]=x; return y; } } void fri(int x) { if(t[rt[x]]!=x)frid.push(x); p[x]=-1; r[x]=0; k[x]=0; if(t[rt[x]]==x&&stan[rt[x]]=='?')stan[rt[x]]='1'; for(int i=0;i<(int)v[x].size();i++) { int neo=v[x][i]; if(p[neo]!=-1)fri(neo); } v[x].clear(); return; } int fin(int x) { if(p[x]==-1)return x; p[x]=fin(p[x]); return p[x]; } void uni(int x,int y) { x=fin(x); y=fin(y); if(x==y) { fri(x); } else { v[x].push_back(y); v[y].push_back(x); if(r[x]>=r[y]) { p[y]=x; k[x]+=k[y]+1; if(r[x]==r[y])r[x]++; } else if(r[x]<r[y]) { p[x]=y; k[y]+=k[x]+1; } } return; } int main() { std::ios_base::sync_with_stdio(0); cin>>n>>q; t.resize(n+3,0); stan.resize(n+3,'0'); for(int i=1;i<=n;i++)t[i]=nev(i); for(int i=0;i<q;i++) { cin>>c; if(c=='+') { cin>>a>>b; stan[a]='?'; stan[b]='?'; uni(t[a],t[b]); } else if(c=='-') { cin>>a; stan[a]='0'; t[a]=nev(a); } else if(c=='?') { cin>>a; cout<<stan[a]; } } return 0; } |