6492: Connectivity

6492: Connectivity

时间限制: 1 Sec   内存限制: 128 MB
提交: 128   解决: 34
[ 提交][ 状态][ 讨论版][命题人: admin]

题目描述

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)

输入

The input is given from Standard Input in the following format:
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.

来源

ABC049&ARC065 

题意:

有公路和铁路两种路,走公路只能走公路,走铁路只能走铁路,求每个城市既能通过公路到达,又能通过铁路到达城市的个数,(城市既可以通过公路到达,又可以通过铁路到达自己)。

思路

并查集,求一下每个城市在公路并查集中的编号,铁路并查集中的编号,然后统计同属于这两个编号的城市个数。


#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
int fa[maxn],ma[maxn];
void init(){
    for (int i=0;i<maxn;i++) fa[i]=i,ma[i]=i;
}
int fnd(int *k,int x){
    return x==k[x]?x:k[x]=fnd(k,k[x]);
}
void Union(int *k,int x,int y){
    int fx=fnd(k,x),fy=fnd(k,y);
    if(fx!=fy) k[fy]=fx;
}
map<pair<int,int>,int>mp;
int main(){
    int n,k,l,u,v;
    init();
    scanf("%d%d%d",&n,&k,&l);
    while(k--){
        scanf("%d%d",&u,&v);
        Union(fa,u,v);
    }
    while(l--){
        scanf("%d%d",&u,&v);
        Union(ma,u,v);
    }
    for (int i=1;i<=n ; i++)  mp[make_pair(fnd(fa,i),fnd(ma,i))]++;
    for (int i=1;i<n;i++) printf("%d ",mp[make_pair(fnd(fa,i),fnd(ma,i))]);
    printf("%d\n",mp[make_pair(fnd(fa,n),fnd(ma,n))]);
    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值