思考: 首先我感觉这道题目不容易的地方就是表示三种物种的相对关系,以及关系之间的相互转化,更新。看了一个网友分享的思路,感觉很不错。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 50010;//动物个数的最大值
///指明父节点与自己的关系,0同类,1被吃,2吃父
const int SAME = 0;
const int ENEMY = 1;
const int FOOD = 2;
struct Animal
{
int parent;
int num;
int relation;
};
Animal ani[maxn];
int ans;
int findParent(Animal* node) {
///Wrong Answer 因为这个函数写错了
///这个函数得是“自洽的”
///就是说,得保证每个元素的父亲的relation是对的
///再算自己的relation
///因为自己的relation和父亲的relation有关
///这就是为什么要先findParent再relation更新的原因
int tmp;
if( node->parent == node->num )
return node->parent;
tmp = node->parent;
#ifdef DBG
printf("Animal %d s Parent is %d\n",node->num,node->parent);
#endif
// node->relation = ( ani[node->parent].relation + node->relation ) % 3;
node->parent = findParent(&ani[node->parent]);
node->relation = ( ani[tmp].relation + node->relation ) % 3;
return node->parent;
}
void Union(int x, int y, int a, int b, int d) { //NB.
ani[b].parent = a;
///rootY.parent = rootX.parent;
ani[b].relation =( (3 - ani[y].relation) + (d - 1) + ani[x].relation) % 3;
}
void init_Animal(int n) {
for(int i = 1 ; i <= n ; i++) {
ani[i].num = i;
ani[i].parent = i;
ani[i].relation = SAME;
}
}
int main()
{
int N, K;
int d, X, Y;
scanf("%d%d",&N, &K);
init_Animal(N);
for(int i = 0; i < K; i++) {
scanf("%d%d%d",&d, &X, &Y);
if( X > N || Y > N)
ans++;
else {
if(d == 2 && X == Y)
ans++;
else {
int a = findParent(&ani[X]);
int b = findParent(&ani[Y]);
if ( a != b ) {
///x,y不在同一集合中
Union(X,Y,a,b,d);
}
else { /// x, y in the same set.
switch(d) {
case 1:
if(ani[X].relation != ani[Y].relation)
ans++;
break;
case 2:
if(((ani[Y].relation + 3 - ani[X].relation) % 3 ) != 1)
ans++;
break;
}
}
}
}
}
printf("%d\n",ans);
return 0;
}
URL:http://blog.csdn.net/c0de4fun/article/details/7318642/