[Explanations] luogu p2078 friend

Disjoint-set

Summary:
1. find two disjoint-set can be used in an array, a set of check and update FA [] array to;

2. find whether the two values ​​are the same ancestor when using Find (), without FA [] array is determined, it is possible path to a value which is not compressed;

3.a, b companies are likely to be male or female

#include<bits/stdc++.h>
using namespace std;
int n, m, q, p, a, b, s1, s2;
int fa[10005];

int find(int x)
{
    if(fa[x] == x) return x;
    return fa[x] = find(fa[x]);
}

void hb(int x, int y)
{
    if(find(x) != find(y)) fa[find(y)] = find(x);
}

int main()
{
    cin >> n >> m >> p >> q;
    for(int i = 1; i <= n; i++) fa[i] = i;
    for(int i = 1; i <= p; i++)
    {
        cin >> a >> b;
        if(a < 0) a = -a, b = -b;
        hb(a, b);
    }
    for(int i = 1; i <= n; i++)
        if(find(i) == find(1)) s1++;
    for(int i = 1; i <= m; i++) fa[i] = i;
    for(int i = 1; i <= q; i++)
    {
        cin >> a >> b;
        if(a < 0) a = -a, b = -b;
        hb(a, b);
    }
    for(int i = 1; i <= m; i++)
        if(find(i) == find(1)) s2++;
    cout << min(s1, s2);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/lovezxy520/p/11567804.html