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 1182 食物链(并查集)解题报告(转)
- 【解题报告】 POJ 1182 食物链 并查集的经典应用+相对位置
- poj 1182 食物链(并查集)解题报告(转)
- POJ 虫子的生活 解题报告 (种类并查集)
- poj 食物链(种类并查集)(思路)
- poj 1182食物链【种类并查集】
- 【原】 POJ 1611 The Suspects 并查集 解题报告
- poj 食物链 种类并查集
- poj 1733 Parity game 并查集 解题报告
- poj 3228 Gold Transportation 最小生成树+带权并查集 解题报告
- POJ-1182 食物链 (种类并查集)
- poj 食物链(种类并查集)(思路)
- NOI2001年-食物链-并查集-解题报告
- POJ-1182-食物链 解题报告
- 解题报告:POJ_1703Find them, Catch them 并查集
- poj 食物链(种类并查集)(思路)
- poj 1182 食物链 (种类并查集经典题)
- poj1182 食物链 种类并查集 经典题
- poj 食物链(种类并查集)(思路)
- POJ 1182 食物链 种类并查集