其他分享
首页 > 其他分享> > POJ1182 食物链 ——并查集** 经典题目

POJ1182 食物链 ——并查集** 经典题目

作者:互联网

​​​​​​POJ1182

POJ-1182 食物链_飘过的小牛-CSDN博客

注意find函数的temp

// Decline is inevitable,
// Romance will last forever.
// POJ1182
//#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <deque>
#include <vector>
using namespace std;
#define mst(a, x) memset(a, x, sizeof(a))
#define INF 0x3f3f3f3f
#define mp make_pair
#define pii pair<int,int>
#define fi first
#define se second
#define ll long long
//#define int long long
const int maxn = 5e4 + 10;
const int maxm = 25;
const int P = 1e9 + 7;
int fa[maxn];
struct node {
    int pre;             //父节点
    int re;             //与父节点关系 0:同类 1:被父节点吃 2:吃根节点
}p[maxn];
int n, m, k;
int find(int x) {
    if(x == p[x].pre) return x;
    int temp = p[x].pre;
    p[x].pre = find(temp); //*
    p[x].re = (p[x].re + p[temp].re) % 3;
    return p[x].pre;
}
void merge(int x, int y) {
    x = find(x);
    y = find(y);
    if(x != y)
        fa[x] = y;
}
void init() {
    for(int i = 0; i <= n; i++) {
        p[i].pre = i;
        p[i].re = 0;
    }
}
void solve() {
    scanf("%d%d", &n, &k);
    int ope, a, b;
    int root1, root2;
    int sum = 0; //假话数量
    init();
    while(k--) {
        scanf("%d%d%d", &ope, &a, &b);
        if(a > n || b > n) {
            sum++;
            continue;
        }
        if(ope == 2 && a == b) {
            sum++;
            continue;
        }
        root1 = find(a);
        root2 = find(b);
        if(root1 != root2) {
            p[root2].pre = root1;
            p[root2].re = (3 + (ope-1)+p[a].re-p[b].re) % 3;
        }
        else {
            if(ope == 1 && p[a].re != p[b].re) {
                sum++;
                continue;
            }
            if(ope == 2 && ((3 - p[a].re + p[b].re) % 3 != ope - 1)) {
                sum++;
                continue;
            }
        }
    }
    printf("%d\n", sum);
}
signed main() {
//    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//    int T; scanf("%d", &T); while(T--)
//    int T; cin >> T; while(T--)
    solve();
    return 0;
}

标签:pre,食物链,re,POJ1182,查集,int,include,find,define
来源: https://blog.csdn.net/m0_59273843/article/details/120577450