您的位置:首页 > 编程语言 > C语言/C++

Poj 食物链 解题报告 (种类并查集)

2017-12-15 00:19 519 查看
题目链接:http://dsalgo.openjudge.cn/tree/5/

种类并查集,思路以及细节在代码和注释中。

#include <cstdio>

const int MAXN = 50010;

int fake; //记录假话个数
int Set[MAXN]; //并查集的父节点
int relaWithFarther[MAXN]; //0 同类,1吃,2被吃,由这样的定义可知相反关系计算方法为,若A和B关系为X,则B和A的关系为(3-X)%3,注意这里的关系不是对称的。

void ini()
{
for(int i = 0; i < MAXN; ++i)
{
Set[i] = i;
relaWithFarther[i] = 0;
}
}

//一下“->”指吃
//注意如何计算本节点与树根(即将成为本节点的父节点)的关系,由向量相加原理可得
//relaWithFarther[node] = (relaWithFarther[node] + relaWithFarther[Set[node]])%3,
//这里模3是因为在这里如果A->B->C,即relationWithFarther[A]=2, relationWithFarther[B]=2,
//得到随后的relationWithFarther[A]=1。
int find(int node)
{
if(Set[node] == node)
return node;
int end = find(Set[node]);
int rela = relaWithFarther[node] + relaWithFarther[Set[node]];
relaWithFarther[node] = rela % 3;
Set[node] = end;
return end;
}

void Union(int nodeA, int nodeB, int relation)
{
int endA = find(nodeA);
int endB = find(nodeB);
//注意因为路径压缩,nodeA和nodeB的父节点已经转变。
if(endA == endB)
{
//此时应有的关系为rela,即有nodeA与endA的关系和nodeB与endB的关系可得nodeA和nodeB的关系,举个例子,A->B<-C可得A和B同类,有A与B的关系加上B和C的关系再模3得到。
int rela = relaWithFarther[nodeA] + (3-relaWithFarther[nodeB])%3;
rela = rela % 3;
if(relation != rela)
{
++fake;
return ;
}
}
Set[endA] = endB;
//见下图:
//A---B
//|   |
//C---D
//由向量相加可得relation(A,B) = relation(A,C)+relation(C,D)+relation(D,B)
relaWithFarther[endA] = ((3-relaWithFarther[nodeA])%3 + relaWithFarther[nodeB] + relation)%3;
}

int main()
{
ini();
fake = 0;
int m, n;
int nodeA, nodeB, relation;
scanf("%d %d", &m, &n);
for(int i = 0; i < n; ++i)
{
scanf("%d %d %d", &relation, &nodeA, &nodeB);
if((nodeA == nodeB && relation == 2) || nodeA > m || nodeB > m){
fake++;
continue;
}
Union(nodeA, nodeB, relation-1);
}
printf("%d\n", fake);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj c++