1. 程式人生 > >ALDS1_11_D Connected Components dfs或bfs或並查集

ALDS1_11_D Connected Components dfs或bfs或並查集

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

此題我一開始用的dfs, 然後超時, 發現需要在查詢之前確定是否連通,於是乎想到了並查集。。 。做完發現並查集是真的快。 。dfs寫了一遍, 但是不如並查集快。 。。

dfs:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int maxn=100005;
int n,m,q;
int num;
vector<int>ve[maxn];
int col[maxn];
void init()
{
    num=0;
    memset (col,0,sizeof(col));
}
void dfs(int x,int nm)
{
     col[x]=nm;
     for (int i=0;i<ve[x].size();i++)
     {
         int z=ve[x][i];
         //避免陷入死遞迴
         if(!col[z])
            dfs(z,nm);
     }
}
void Find ()
{
    for (int i=0;i<n;i++)
        if(!col[i])
            dfs(i,++num);
}
int main()
{
    scanf("%d%d",&n,&m);
    init();
    while (m--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        ve[x].push_back(y);
        ve[y].push_back(x);
    }
    Find();
    scanf("%d",&q);
    while (q--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        col[x]==col[y]?printf("yes\n"):printf("no\n");
    }
    return 0;
}

並查集:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int maxn=100005;
int n,m,q;
int a[maxn];
void init()
{
    for (int i=0;i<n;i++)
        a[i]=i;
}
//尋找父節點
int Find(int x)
{
    if(x==a[x])
        return x;
    return a[x]=Find(a[x]);
}
//合併
void unit (int x,int y)
{
    int parx=Find(x);
    int pary=Find(y);
    if(parx!=pary)
        a[parx]=pary;
}
int main()
{
    scanf("%d%d",&n,&m);
    init();
    while (m--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        unit(x,y);
    }
    scanf("%d",&q);
    while (q--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        Find(x)==Find(y)?printf("yes\n"):printf("no\n");
    }
    return 0;
}