Motion rules (16) - and check the basic questions - relatives (Relations)

Relatives

Maybe you don't know that one of your friends is your relative. He could be your great-grandfather's grandpa's son-in-law's nephew's cousin's grandson. If a complete family tree is available, it should be feasible to determine whether two people are related, but if the nearest common ancestor of two people is several generations away from them, making the family tree very large, then it is beyond the reach of human beings. In this case , the best helper is the computer.

In order to simplify the problem, you will get some information about relatives, such as Mary and Tom are relatives, Tom and Ben are relatives, and so on. From this information, you can deduce that Marry and Ben are related. Please write a program to answer the questions about relatives we care about as quickly as possible.

Reference Input Output Format The input consists of two parts.

The first part starts with N , M. N is the number of people involved in the problem (1 N 20000) . These people are numbered 1,2,3, ,N . There are M lines below (1 M 1000000) , each line has two numbers ai, bi , which means that ai and bi are known to be relatives .

The second part starts with Q. The following Q lines have Q inquiries (1 Q 1 000 000) , and each line is ci, di , indicating whether ci and di are relatives.

For each query ci, di , if ci and di are relatives, output Yes , otherwise output No.

Sample input and output

enter

10 7

2 4

5 7

1 3

8 9

1 2

5 6

2 3

3

3 4

7 10

8 9

output

Yes

No

Yes

#include <cstdio>
#include <iostream>
using namespace std;
int fa[20001], n, m, x, y, r1, r2;
int find(int u)
{
    return fa[u] == u ? u : fa[u] = find(fa[u]);
}
int read()
{
    int x = 0;
    char ch = getchar();
    while (!isdigit(ch))
        ch = getchar();
    while (isdigit(ch))
        x = x * 10 + ch - 48, ch = getchar();
    return x;
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        fa[i] = i;
    for (int i = 1; i <= m; i++)
    {
        x = read();
        y = read();
        r1 = find(x);
        r2 = find(y);
        if (r1 != r2)
            fa[r1] = r2;
    }
    cin >> m;
    for (int i = 1; i <= m; i++)
    {
        x = read();
        y = read();
        r1 = find(x);
        r2 = find(y);
        if (r1 == r2)
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/hdq1745/article/details/126034362