Disjoint-set: food chain

Topic link: https: //www.acwing.com/problem/content/242/
meaning of the questions : There are three types of animals in the animal kingdom A, B, C, three types of animal food chain constitute an interesting ring.
A food B, B eat C, C eat A.
Animals prior N, number to 1-N.
Each animal is A, B, C in kind, but we do not know it in the end is what kind of.
It was carried out with two versions of this trophic animals consisting of N Description:
The first argument is "1 XY", represents the X and Y are similar.
The second argument is "2 XY", X represents eat Y.
This person for N animals, with the above two statements, one sentence by sentence to say K, K this sentence some true, some false.
When one of the following three words, this sentence is a lie, the truth is otherwise.
1) if the current true, then some of the previous conflicts, is lie;
2), then the current X or Y is larger than N, is lie;
3) X represents eat, then the current X, is lie.
Your task is given according to the total number of N and K words, the output of lies.
Data range
1≤N≤5e4,
0≤K≤1e5
input sample:
100. 7
. 1 101. 1
2. 1 2
2 3 2
2 3 3
. 1. 1 3
2 3. 1
. 1. 5. 5
Output Sample:
3
Thinking: After this question can be classified with a disjoint-set to resolve, with each point from the root to the root to represent its relationship with the total on three categories, then put three on the distance modulus can put each point classified.
Code:

#include <iostream>

using namespace std;

const int N = 50010;

int n, m;
int p[N], d[N];

int find(int x)
{
    if (p[x] != x)
    {
        int t = find(p[x]);
        d[x] += d[p[x]];
        p[x] = t;
    }
    return p[x];
}

int main()
{
    scanf("%d%d", &n, &m);

    for (int i = 1; i <= n; i ++ ) p[i] = i;

    int res = 0;
    while (m -- )
    {
        int t, x, y;
        scanf("%d%d%d", &t, &x, &y);

        if (x > n || y > n) res ++ ;
        else
        {
            int px = find(x), py = find(y);
            if (t == 1)
            {
                if (px == py && (d[x] - d[y]) % 3) res ++ ;
                else if (px != py)
                {
                    p[px] = py;
                    d[px] = d[y] - d[x];
                }
            }
            else
            {
                if (px == py && (d[x] - d[y] - 1) % 3) res ++ ;
                else if (px != py)
                {
                    p[px] = py;
                    d[px] = d[y] + 1 - d[x];
                }
            }
        }
    }

    printf("%d\n", res);

    return 0;
}
Published 62 original articles · won praise 0 · Views 951

Guess you like

Origin blog.csdn.net/Satur9/article/details/104089449