Problem Statement
There are N cities. There are also K roads and L railways, extending between the cities. The i-th road bidirectionally connects the pi-th and qi-th cities, and the i-th railway bidirectionally connects the ri-th and si-th cities. No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.
We will say city A and B are connected by roads if city B is reachable from city Aby traversing some number of roads. Here, any city is considered to be connected to itself by roads. We will also define connectivity by railways similarly.
For each city, find the number of the cities connected to that city by both roads and railways.
Constraints
- 2≦N≦2*105
- 1≦K,L≦105
- 1≦pi,qi,ri,si≦N
- pi<qi
- ri<si
- When i≠j, (pi,qi)≠(pj,qj)
- When i≠j, (ri,si)≠(rj,sj)
Input
The input is given from Standard Input in the following format:
N K L p1 q1 : pK qK r1 s1 : rL sL
Output
Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.
Sample Input 1
4 3 1 1 2 2 3 3 4 2 3
Sample Output 1
1 2 2 1
All the four cities are connected to each other by roads.
By railways, only the second and third cities are connected. Thus, the answers for the cities are 1,2,2 and 1, respectively.
Sample Input 2
4 2 2 1 2 2 3 1 4 2 3
Sample Output 2
1 2 2 1
Sample Input 3
7 4 4 1 2 2 3 2 5 6 7 3 5 4 5 3 4 6 7
Sample Output 3
1 1 2 1 2 2 2
就用并查集暴力预处理出两张图的连通情况,然后每个并查集开个set,暴力枚举每个点,在两个图中查交集就行。注意每次查出来的交集里面的点一并记录答案并删除。
#include<cstdio> #include<set> using namespace std; int fa[2][200010],__rank[2][200010]; int findroot(bool op,int x) { return x==fa[op][x] ? x : fa[op][x]=findroot(op,fa[op][x]); } void Union(bool op,int U,int V) { if(__rank[op][U]<__rank[op][V]) fa[op][U]=V; else { fa[op][V]=U; if(__rank[op][U]==__rank[op][V]) ++__rank[op][U]; } } int n,m,K; bool vis[200010]; int anss[200010]; set<int>S[2][200010]; typedef set<int>::iterator ITER; int path[200010],e; int main() { int x,y; scanf("%d%d%d",&n,&m,&K); for(int i=1;i<=n;++i) fa[0][i]=fa[1][i]=i; for(int i=1;i<=m;++i) { scanf("%d%d",&x,&y); int f1=findroot(0,x),f2=findroot(0,y); if(f1!=f2) Union(0,f1,f2); } for(int i=1;i<=K;++i) { scanf("%d%d",&x,&y); int f1=findroot(1,x),f2=findroot(1,y); if(f1!=f2) Union(1,f1,f2); } for(int i=0;i<=1;++i) for(int j=1;j<=n;++j) S[i][findroot(i,j)].insert(j); for(int i=1;i<=n;++i) if(!vis[i]) { e=0; int rt[2]; bool o=0; rt[0]=findroot(0,i); rt[1]=findroot(1,i); if(S[0][rt[0]].size()>S[1][rt[1]].size()) o=1; set<int> tS=S[o][rt[o]]; for(ITER it=tS.begin();it!=tS.end();++it) if(S[o^1][rt[o^1]].find(*it)!=S[o^1][rt[o^1]].end()) { S[o][rt[o]].erase(*it); S[o^1][rt[o^1]].erase(*it); path[++e]=(*it); vis[*it]=1; } for(int j=1;j<=e;++j) anss[path[j]]=e; } for(int i=1;i<n;++i) printf("%d ",anss[i]); printf("%d ",anss[n]); return 0; }