upc ABC049&ARC065 Connectivity(并查集+dfs)

6492: Connectivity

时间限制: 1 Sec   内存限制: 128 MB
提交: 122   解决: 30
[ 提交][ 状态][ 讨论版][命题人: 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.

来源

【题意】

给出一个无向图,K条公路,L条铁路。

问对于每个点,满足<公路与铁路均能到达的点>的点数(包括本身)

【分析】

用并查集维护公路图,可以方便的知道那些点属于同一个连通块。

对铁路图进行第一次dfs,每个铁路连通块中,对每个点所属的公路连通块计数+1,第二次dfs,将连通块计数赋值给每个该铁路连通块中的点。

【代码】

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
struct node{
    int t,next;
}e[N];
int head[N],cnt;
void init(){
    memset(head,-1,sizeof(head));
    cnt=0;
}
void add(int u,int v){
    e[cnt]=node{v,head[u]};
    head[u]=cnt++;
}
int fa[N];
int father(int x){return x==fa[x]?x:fa[x]=father(fa[x]);}
int join(int x,int y){x=father(x);y=father(y);if(x!=y)fa[x]=y;}
void initfa(int n){for(int i=1;i<=n;i++)fa[i]=i;}

int vis[N],ans[N];

void dfs1(int u,int tag,map<int,int>&M)  //块计数
{
    if(vis[u]==tag)return;
    vis[u]=tag;
    M[father(u)]++;
    for(int i=head[u];~i;i=e[i].next)
    {
        dfs1(e[i].t,tag,M);
    }
}

void dfs2(int u,int tag,map<int,int>&M)
{
    if(vis[u]==tag)return;
    vis[u]=tag;
    ans[u]+=M[father(u)];
    for(int i=head[u];~i;i=e[i].next)
    {
        dfs2(e[i].t,tag,M);
    }
}

int main()
{
    int n,k,L,u,v;
    scanf("%d%d%d",&n,&k,&L);
    init();
    initfa(n);
    while(k--){
        scanf("%d%d",&u,&v);
        join(u,v);
    }
    while(L--){
        scanf("%d%d",&u,&v);
        add(u,v);
        add(v,u);
    }
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++) if(!vis[i])
    {
        map<int,int>M;
        dfs1(i,i,M);
        dfs2(i,-i,M);
    }
    for(int i=1;i<=n;i++)
        printf("%d%c",ans[i],i<n?' ':'\n');
}


猜你喜欢

转载自blog.csdn.net/winter2121/article/details/80508140
UPC
今日推荐