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

题目链接: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;

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值