标签:
Description
Input
Output
Sample Input
100 7 1 101 1 2 1 2 2 2 3 2 3 3 1 1 3 2 3 1 1 5 5
Sample Output
3
解题思路:将关系转化成偏移量。x->y 偏移量为 0 表示同类。 x->y 偏移量为 1 表示 y 被 x 吃。 x->y 偏移量为2表示 x 被 y 吃。结点x的关系域 rela 表示父亲结点 fax 到 x的偏移量。 可以参考下面的博客学习。http://blog.csdn.net/niushuai666/article/details/6981689。
#include<stdio.h> #include<string.h> #include<algorithm> #include<iostream> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 1e5+200; struct Animal{ int pa,rela; }anims[maxn]; int n; void init(){ for(int i = 0; i <= n; i++){ anims[i].pa = i; //初始化父亲域 anims[i].rela = 0; //初始化关系域 } } int Find(int x){ if(anims[x].pa == x) return x; int tmp = anims[x].pa; //记录x原来的父亲 anims[x].pa = Find( tmp ); //将x连到根上 anims[x].rela = ( anims[tmp].rela + anims[x].rela)%3; //x与根的偏移量就是根到x原父节点的偏移量+父节点到x的偏移量 return anims[x].pa; //返回根节点 } int main(){ int k; scanf("%d%d",&n,&k); init(); int a,x,y; int cnt = 0; for(int i = 0;i < k; i++){ scanf("%d%d%d",&a,&x,&y); if(x>n||y>n){ cnt++; }else if( a == 2&& x == y){ cnt++; }else { int rootx = Find(x); //x的根 int rooty = Find(y); //y的根 if(rootx == rooty){ //如果根相同,说明在一个集合中,有一定关系 //如果根到x、y的偏移量相同,说明x、y同类 if(a == 1&& anims[x].rela != anims[y].rela){ cnt++; }else if(a == 2){ // x到y的偏移量等于x到根的偏移量加上根到y的偏移量 if( a - 1 != (3 + anims[y].rela - anims[x].rela)%3 ){ cnt++; } } }else{ //合并 //让x的根作为rooty集合的根 anims[rooty].pa = rootx; //x的根rootx到rooty的偏移量为rootx到x的偏移量(anims[x].rela) + x到y的偏移量(a-1) + y到rooty的偏移量(-anims[y].rela) anims[rooty].rela = (3 + anims[x].rela + a-1 - anims[y].rela )%3; } } } printf("%d\n",cnt); return 0; }
标签:
原文地址:http://www.cnblogs.com/chengsheng/p/4906600.html