标签:
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
题解:第一次做,感觉无从下手。原来有公式。那就是:0表示同类,1表示x吃y,2表示x被y吃。那么当我们知道(x,y)和(y,z)的关系,我们就能得到x和z的关系。为什么呢?因为可以推出来。总共就9种情况((x,y),(y,z)的关系)。(0,0),(01),(02),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2),当你穷举所有情况,你会发现(x,z)=((x,y) + (y,z))%3;神奇吧。还有(y,x) = 3 - (x,y);
1.当输入的x,y属于同一集合,此时x,y的关系可以通过共同的根推出来,因为知道了(x,root),(y,root)的关系了。如果推出来的关系和输入的d不一样,说明这是假话。
2.当x,y不属于同一个集合,说明这是真话,因为以前的话和这句话不矛盾啊,我靠。以前如果x,y有关系就会是同一个集合了。然后计算x,y的根之间关系。我们知道了(x,y)(因为这是真话),(y,fy),(x,fx).那么要想得到(fy,fx),需要知道(fy,y),(y,x)->(fy,x),在知道(x,fx),就得到了(fy,fx);这里自己去推吧。我推的和别人的不一样。这里需要注意,不管x,y有没有根,都会符合推出来的公式,因为初始化是0,带进去公式结果一样。可以自己带进去试试。我的公式在代码里面。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int pre[500005];
int rank[500005];
int sum;
int find(int x)
{
	if(x == pre[x])
	{
		return x;
	}
	int fa = pre[x];
	pre[x] = find(pre[x]);
	rank[x] = (rank[x] + rank[fa]) % 3;  //和新的根的关系由原来的根节点和现在的根节点推出来 
	return pre[x]; 
}
bool solve(int d,int x,int y)
{
	int xx = find(x);
	int yy = find(y);
	if(xx == yy)
	{
		if((rank[x] - rank[y] + 3) % 3 == d)
		{
			return true;
		}
		return false;
	}
	pre[yy] = xx;
	rank[yy] = (6 - d - rank[y] + rank[x]) % 3;  //公式 
	return true;
}
int main()
{
	int n,m;
	//while(scanf("%d%d",&n,&m) != EOF)  //居然只有一组数据,我靠,用这个wrong 
	{
		scanf("%d%d",&n,&m);
		sum = 0;
		int d,x,y;
		for(int i = 1;i <= n;i++)
		{
			pre[i] = i;
			rank[i] = 0;
		}
		for(int i = 0;i < m;i++)
		{
			scanf("%d%d%d",&d,&x,&y);
			if(x <= 0 || x > n || y <= 0 || y > n)
			{
				sum++;
				continue;
			}
			if(!solve(d - 1,x,y))
			{
				sum++;
			}
		}
		
		printf("%d\n",sum);
	}
	return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wang2534499/article/details/48008937