题目描述
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 A by 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)
We will say city A and B are connected by roads if city B is reachable from city A by 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)
输入
The input is given from Standard Input in the following format:
N K L
p1 q1
:
pK qK
r1 s1
:
rL sL
N K L
p1 q1
:
pK qK
r1 s1
:
rL sL
输出
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.
样例输入
4 3 1
1 2
2 3
3 4
2 3
样例输出
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.
来源
题目意思为有n个城市,每两个城市之间有路连接有铁路和公路两种方式,问每个城市,和它有两种相连方式的城市有多少个,自己和自己相连。题目可以看成是一个图,而且建图时必须两个点之间有两种方式才建一条边,然后对每个点求一下连通块,求连通块可以不用dfs或者bfs,可以使用并查集来求,先把有公路相连的点用并查集关联起来,然后将用铁路相连的点用并查集关联,最后分别求一下每个点在并查集中的对应的点,然后用STL中的map保存两个值,将map的值加一,两个点可以用pair<int, ,int>保存,最后map中保存的值就是最终答案,每个点的答案就是按之前所说的方法把加一变为直接输出。注意并查集写法,我就因为这个一直re。
AC代码:
#include<stdio.h>
#include<iostream>
#include<map>
using namespace std;
const int maxn = 2e6 + 10;
typedef pair<int, int> P;
int fa[maxn], ma[maxn];
void init(int n)
{
for(int i = 0; i <= n; ++ i)
{
fa[i] = i;
ma[i] = i;
}
}
int find(int* fa, int x)
{
if(fa[x] == x)
{
return fa[x];
}
return fa[x] = find(fa, fa[x]);
}
void unin(int a, int b, int* fa)
{
a = find(fa, a);
b = find(fa, b);
fa[a] = b;
}
map<P, int>ans;
int main()
{
int n, k, l;
while(scanf("%d%d%d", &n, &k, &l) != EOF)
{
init(n);
ans.clear();
for(int i = 0; i < k; ++ i)
{
int a, b;
scanf("%d%d", &a, &b);
unin(a, b, ma);
}
for(int i = 0; i < l; ++ i)
{
int a, b;
scanf("%d%d", &a, &b);
{
unin(a, b, fa);
}
}
for(int i = 1; i <= n; ++ i)
{
ans[make_pair(find(ma, i), find(fa, i))]++;
}
for(int i = 1; i <= n; ++ i)
{
i == n ? printf("%d\n", ans[make_pair(find(ma, i), find(fa, i))]) : printf("%d ", ans[make_pair(find(ma, i), find(fa, i))]);
}
}
return 0;
}