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 110 111 112 113
| #include<algorithm> #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> #include<vector> #include<cstdio> #include<cmath> #include<queue> using namespace std;
inline const int Get_Int() { int num=0,bj=1; char x=getchar(); while(x<'0'||x>'9') { if(x=='-')bj=-1; x=getchar(); } while(x>='0'&&x<='9') { num=num*10+x-'0'; x=getchar(); } return num*bj; }
const int maxn=200005;
int n,m,q,prt[maxn],Ans[maxn],Depth[maxn],father[maxn],Size[maxn],top=0,cnt=0; struct Point { int x,y,opt; Point(int _x=0,int _y=0):x(_x),y(_y),opt(0) {} } a[maxn],b[maxn]; vector<int>edges[maxn];
void AddEdge(int x,int y) { edges[x].push_back(y); edges[y].push_back(x); }
int Get_Father(int x) { if(father[x]==x)return x; return father[x]=Get_Father(father[x]); }
void Dfs(int Now,int fa) { prt[Now]=fa; Depth[Now]=Depth[fa]+1; for(int i=0; i<edges[Now].size(); i++) { int Next=edges[Now][i]; if(Next==fa)continue; Dfs(Next,Now); } }
int LCA(int x,int y) { x=Get_Father(x); y=Get_Father(y); if(Depth[x]<Depth[y])swap(x,y); while(Get_Father(x)!=Get_Father(y)) { int Nowx=Get_Father(x),Nowy=Get_Father(prt[Nowx]); if(Nowx!=Nowy) { Size[Nowy]+=Size[Nowx]; father[Nowx]=Nowy; } x=Nowy; if(Depth[x]<Depth[y])swap(x,y); } return Get_Father(x); }
int main() { n=Get_Int(); m=Get_Int(); q=Get_Int(); for(int i=1; i<=n; i++)father[i]=i; for(int i=1; i<=m; i++) { int x=Get_Int(),y=Get_Int(); int fx=Get_Father(x),fy=Get_Father(y); if(fx!=fy) { father[fy]=fx; AddEdge(x,y); } else b[++cnt]=Point(x,y); } for(int i=1; i<=q; i++) { int x=Get_Int(),y=Get_Int(); int fx=Get_Father(x),fy=Get_Father(y); if(fx!=fy) { father[fy]=fx; AddEdge(x,y); a[i].opt=1; } a[i].x=x; a[i].y=y; } for(int i=1; i<=n; i++) { int x=Get_Father(1),y=Get_Father(i); if(x!=y) { father[y]=x; AddEdge(1,i); } } Dfs(1,0); for(int i=1; i<=n; i++)father[i]=i,Size[i]=1; for(int i=1; i<=cnt; i++)LCA(b[i].x,b[i].y); for(int i=1; i<=q; i++) if(a[i].opt!=1) { int lca=LCA(a[i].x,a[i].y); Ans[i]=Size[lca]; } for(int i=1; i<=q; i++) if(a[i].opt==1)puts("No"); else printf("%d\n",Ans[i]); return 0;
|