数据结构与算法MOOC / 第六章 树 练习题(Excercise for chapter6 trees)5:食物链

该博客介绍了数据结构与算法中关于树的应用,具体是处理一道并查集题目,涉及捕食关系的“模3加法”。通过分析“真话假话”的逻辑,构建并查集并维护数组。博客详细讨论了在find和union过程中如何维护数组,并解释了如何判断题目的真假陈述。最后提到了在C/C++编程中处理负数的细节问题。
摘要由CSDN通过智能技术生成

数据结构与算法MOOC / 第六章 树 练习题(Excercise for chapter6 trees)5:食物链

题目链接:http://dsalgo.openjudge.cn/tree/5/

AC代码

#include <cstdio>

using namespace std;
int prev[50001], mem[50001], it_mem;
int tag[50001];

int treeFind(int x) {
   
    if (prev[x] == x)
        return x;
    it_mem = 0;
    while (prev[x] != x) {
   
        mem[it_mem++] = x;
        x = prev[x];
    }
    mem[it_mem] = x;
    while (it_mem--) {
   
        tag[mem[it_mem]] = (tag[mem[it_mem]] + tag[mem[it_mem + 1]]) % 3;
        prev[mem[it_mem]] = x;
    }
    return prev[*mem];
}

bool treeUnion(int t, int x, int y) {
   
    int x_f = treeFind(x), y_f = treeFind(y);
    if (x_f == y_f)
        return (t + tag[y]) % 3 == tag[x];
    prev[x_f] = y_f;
    tag[x_f] = (tag[y] - tag[x] + t + 3) % 3;
    return true;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值