Disjoint-set - food chain

Food chain 
	
animal kingdom there are three types of animal 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", it 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. 
The input format 
of the first two lines are integers N and K, separated by a space. 
K The following three lines each is a positive integer D, X, Y, separated by a space between the two numbers, where D indicates the type of argument. 
If D = 1, it indicates that X and Y are similar. 
If D = 2, then X represents eat Y. 
Output formats 
only one integer representing the number of lies. 
Data range 
1≤N≤500001≤N≤50000, 
0≤K≤1000000≤K≤100000 
Input Sample: 
1007
101. 1. 1
2. 1 2 
2 3 2 
2 3 3 
. 1. 1 3 
2 3. 1 
. 1. 5. 5 
Output Sample: 
3

  

#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] - d[x] + 1;
                }
            }
            
        }
    }
    printf("%d",res);
    return 0;
    
}

  

Guess you like

Origin www.cnblogs.com/luyuan-chen/p/11407116.html