题目链接:http://poj.org/problem?id=1182
详细题解:http://blog.csdn.net/c0de4fun/article/details/7318642 (没有比这篇食物链的结题报告更好的了)
附上我的代码:
#include<cstdio> #define N 55000 int F[N], rel[N]; int fun(int x) { if(x != F[x]) { int fa_x = fun(F[x]); rel[x] = (rel[x] + rel[F[x]]) % 3; F[x] = fa_x; } return F[x]; } void Union(int x, int y, int fa_x, int fa_y,int d) { F[fa_y] = fa_x; rel[fa_y] = (3-rel[y]+(d-1)+rel[x])%3; } int slove(int d, int x, int y) { int fa_x = fun(x); int fa_y = fun(y); if(d == 1) { if(fa_x == fa_y) //在同一个集合内 { if(rel[x] != rel[y]) return 1; else return 0; } else{ Union(x,y,fa_x,fa_y,d); return 0; } } if(d == 2) { if(fa_x == fa_y) { if((rel[y]+3-rel[x])%3 != 1) return 1; else return 0; } else { Union(x,y,fa_x,fa_y,d); return 0; } } } int main () { int n, k, d, x, y; scanf("%d %d", &n, &k); for(int i = 1; i <= n; i++) F[i] = i, rel[i] = 0; int ans = 0; while(k--) { scanf("%d %d %d", &d, &x, &y); if(x > n||y > n){ans++; continue;} if(d == 2 && x == y){ans++; continue;} ans += slove(d,x,y); } printf("%d\n", ans); return 0; }