食物链 || 带权并查集
0:同类
1:吃
2:被吃
w[x]表示x和它爸爸的关系
#include <cstdio> using namespace std; const int maxn=5e4+3; int f[maxn], w[maxn]; void init(int n) { for(int i = 1; i <= n; ++i) f[i] = i, w[i] = 0; } int find(int x) { if(x == f[x]) return x; int tmp = f[x]; f[x] = find(f[x]); w[x] = (w[x] + w[tmp] + 3) % 3;//这里其实不用+3,因为w[i]为0-2的数 return f[x]; } int main() { int n, k, d, x, y, cnt = 0; scanf("%d %d", &n, &k); init(n); for(int i = 0; i < k; ++i) { scanf("%d %d %d", &d, &x, &y); if(x > n || y > n || (d == 2 && x == y)) { ++cnt; continue; } int xx = find(x), yy = find(y); if(xx == yy) { if((w[x] - w[y] + 3) % 3 != d - 1) ++cnt; } else { f[xx] = yy; w[xx] = (w[y] - w[x] + d - 1 + 3) % 3; } } printf("%d ", cnt); }