数据结构与算法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;