向量法的图看了n遍才明白...我开始还在生推......
代码参考的这位:https://blog.csdn.net/niushuai666/article/details/6981689
主要说一下图
tx -> ty
| |
x -> y
给了x和y的关系,然后要求tx -> ty关系
那就是tx->x + x->y + y->ty
然后后面要pending x和y关系,那就反着来,+3 %3保证区间
/*
POJ 1182
带权值的并查集
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 50010
struct node
{
int pre;
int relation;
};
node p[N];
int find(int x) //查找根结点
{
int temp;
if(x == p[x].pre)
return x;
temp = p[x].pre; //路径压缩
p[x].pre = find(temp);
p[x].relation = (p[x].relation + p[temp].relation) % 3; //关系域更新
return p[x].pre; //根结点
}
int main()
{
int n, k;
int ope, a, b;
int root1, root2;
int sum = 0; //假话数量
scanf("%d%d", &n, &k);
for(int i = 1; i <= n; ++i) //初始化
{
p[i].pre = i;
p[i].relation = 0;
}
for(int i = 1; i <= k; ++i)
{
scanf("%d%d%d", &ope, &a, &b);
if(a > n || b > n) //假话条件2
{
sum++;
continue;
}
if(ope == 2 && a == b) //假话条件3
{
sum++;
continue;
}
root1 = find(a);
root2 = find(b);
if(root1 != root2) // 合并(之前没有关系)
{
p[root2].pre = root1;//2是子结点
p[root2].relation = (3 + (ope - 1) +p[a].relation - p[b].relation) % 3;// ope-1是我们想要的关系
}
//菜成傻逼...巨巨们可以忽略下面的了,向量法看懂了.
//a和b是输入,root1和root2是找到的根节点
/*如果是同类 --> ope == 1, 那么 a 和 b 是同类,找到root2和根节点的关系
有九种可能 (注 a : a的relation)
1.如果都是0,那么都是0
2.如果a 是1,b是0 (被root1吃) 那么root1 吃root2 ,但是根是root1, 关系:1
3.如果a 是0,b是1 (被root2吃) 关系:2
4.如果a 是2 b是0 root1和root2是同类,但是被a吃,那么关系是同类 0
5.如果a 是2 b是1 root1被a吃,root2吃b 关系: 1 root2被根节点吃? a和b是同类 ??? 我没算明白,不过我感觉这种情况不会出现,因为一root1为根节点,那么被吃的永远是子结点,那么根对子结点的关系不存在2???是这样么???
6.如果a 是2 b是2 同类 关系:0
7.如果a 是0 b是2 root2被root1吃 关系:1
8.如果a 是1 b是2 疑问同5.
9.如果都是1 关系同类 :0
我们大概明白了a和b的关系应该怎么算,用a-b+3,然后是ope的关系
如果是a吃b --> ope == 2,那么a吃b
也有九个可能,不列全了...
1.a是1,b是0 a被root1吃,a吃b,b和root2是同类,得到root2吃root1?
然后得到了上述公式.
又看了看题,发现说食物链形成了环,所以,a吃b,b吃c,我们就能得到c吃a了?
好像是酱紫.
*/
/*
p[x].relation=0 ……表示节点x与其父节点rootx的关系是:同类
p[x].relation=1 ……表示节点x与其父节点rootx的关系是:被根结点吃
p[x].relation=2 ……表示节点x与其父节点rootx的关系是:吃根结点
*/
else//验证是否冲突
{
if(ope == 1 && p[a].relation != p[b].relation) //同类,但是a和b对于根节点的关系不相等
{
sum++;
continue;
}
if(ope == 2 && ((3 - p[a].relation + p[b].relation) % 3 != ope - 1))//如果a被b吃,但是a和b对根节点的关系不等于
{
sum++;
continue;
}
}
}
printf("%d\n", sum);
return 0;
}