【并查集】Connectivity @ABC049&ARC065/upcexam6492

Connectivity

时间限制: 1 Sec  内存限制: 128 MB

题目描述

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.

来源

meaning

有N个点,K条公路,L条铁路,每条路连接两个点,输出每个点既能只走公路到达,又能只走铁路到达的点的数量。

solution

对公路,铁路分别建并查集。

统计答案时hash一下,如果两个点之间既能走公路到达,又能走铁路到达,他们的答案肯定是一样的,因为属于同一个交集。

所以我们只需用一个map统计每个交集中点的数量即可。

code

#define IN_LB() freopen("C:\Users\acm2018\Desktop\in.txt","r",stdin)
#define OUT_LB() freopen("C:\Users\acm2018\Desktop\out.txt","w",stdout)
#define IN_PC() freopen("C:\Users\hz\Desktop\in.txt","r",stdin)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const ld INF = 1e37;
const int maxn = 200005;

int pre1[maxn],pre2[maxn];

void init(int number_p,int *setName){
    for(int i=1;i<=number_p;i++){
        setName[i] = i;
    }
}

int query(int x,int *setName){
    return setName[x]==x?setName[x]:setName[x] = query(setName[x],setName);
}

void combine(int x,int y,int *setName){
    query(x,setName)!=query(y,setName)?setName[query(x,setName)]=query(y,setName):0;
}

int main() {
//    IN_LB();
//    ios::sync_with_stdio(false);
    int n,k,l;
    scanf("%d%d%d",&n,&k,&l);
    init(n,pre1);
    init(n,pre2);
    for(int i=0;i<k;i++){
        int p,q;
        scanf("%d%d",&p,&q);
        combine(p,q,pre1);
    }
    for(int i=0;i<l;i++){
        int r,s;
        scanf("%d%d",&r,&s);
        combine(r,s,pre2);
    }
    for(int i=1;i<=n;i++){
        query(i,pre1);
        query(i,pre2);
    }
    map<pair<int,int>,int> mp;
    for(int i=1;i<=n;i++){
        mp[{pre1[i],pre2[i]}]++;
    }
    for(int i=1;i<=n;i++){
        printf("%d%s",mp[{pre1[i],pre2[i]}],i<n?" ":"
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/NeilThang/p/9356600.html