码迷,mamicode.com
首页 > 其他好文 > 详细

Connectivity

时间:2018-05-27 13:50:06      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:bit   long   cti   set   scan   class   hid   end   ons   

题目描述

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.

嘤语阅读理解.....刚开始读了半天没读懂
即能同时只通过火车和公路连到该城市的城市个数,自己算一个.....
即两个并查集的交集,并查集不难,注意要路径压缩,不然T
用struct写并查集
然后pair表示连接的道路和铁路的根节点
技术分享图片
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=2e5+7;
#define p make_pair
map<pair<int,int>,int>mp;
int sa[maxn],sb[maxn],a1,a2;
struct dsu
{
    int fa[maxn];
    void unit(int n){
        for(int i=1;i<=n;i++){
            fa[i]=i;
        }
    }
    int findset(int a){
        if(fa[a]==a)
        {
            return a;
        }
        return fa[a]=findset(fa[a]);
    }
    void union_(int x,int y){
        a1=findset(x);
        a2=findset(y);
        if(a1!=a2){
            fa[a1]=a2;
        }
    }
};
int main()
{
    int n,k,l,a,b;
    scanf("%d %d %d",&n,&k,&l);
    dsu s1,s2;
    s1.unit(n);
    s2.unit(n);
    for(int i=1;i<=k;i++){
        scanf("%d %d",&a,&b);
        s1.union_(a,b);
    }
    for(int i=1;i<=l;i++){
        scanf("%d %d",&a,&b);
        s2.union_(a,b);
    }
    for(int i=1;i<=n;i++){
        sa[i]=s1.findset(i);
        sb[i]=s2.findset(i);
        mp[p(sa[i],sb[i])]++;
    }
    for(int i=1;i<=n;i++){
        if(i!=1) printf(" ");
        printf("%d",mp[p(sa[i],sb[i])]);
    }
    printf("\n");
    return 0;
}
View Code

 

 

Connectivity

标签:bit   long   cti   set   scan   class   hid   end   ons   

原文地址:https://www.cnblogs.com/smallocean/p/9095566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!