Connected Components (邻接表dfs)

滴答滴答---题目链接 

Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.

Input

In the first line, two integer nn and mm are given. nn is the number of users in the SNS and mm is the number of relations in the SNS. The users in the SNS are identified by IDs 0,1,...,n−10,1,...,n−1.

In the following mm lines, the relations are given. Each relation is given by two integers ss and tt that represents ss and tt are friends (and reachable each other).

In the next line, the number of queries qq is given. In the following qq lines, qq queries are given respectively. Each query consists of two integers ss and tt separated by a space character.

Output

For each query, print "yes" if tt is reachable from ss through the social network, "no" otherwise.

Constraints

  • 2≤n≤100,0002≤n≤100,000
  • 0≤m≤100,0000≤m≤100,000
  • 1≤q≤10,0001≤q≤10,000

Sample Input

10 9
0 1
0 2
3 4
5 7
5 6
6 7
6 8
7 8
8 9
3
0 1
5 9
1 3

Sample Output

yes
yes
no
#include <bits/stdc++.h>
using namespace std;
int n;
const int maxn=100001;
vector<int>g[maxn];
const int NLL=-1;
int color[maxn];
void dfs(int r,int c)
{
    stack<int>s;
    s.push(r);
    color[r]=c;
    while(!s.empty())
    {
        int u=s.top();
        s.pop();
        for(int i=0; i<(int)g[u].size(); i++)//搜索与u顶点相连的点v
        {
            int v=g[u][i];
            if(color[v]==NLL)
            {
                color[v]=c;
                s.push(v);
            }
        }
    }
}
void assigncolor()
{
    int id=1;
    for(int i=0; i<n; i++)
        color[i]=NLL;
    for(int i=0; i<n; i++)
        if(color[i]==NLL)
            dfs(i,id++);
}
int main()
{
    int m,q;
    cin>>n>>m;
    for(int i=0; i<m; i++)
    {
        int x,y;
        cin>>x>>y;
        g[x].push_back(y);
        g[y].push_back(x);

    }
    assigncolor();
    cin>>q;
    while(q--)
    {
        int x,y;
        cin>>x>>y;
        if(color[x]==color[y])
            printf("yes\n");
        else printf("no\n");
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值