POJ 虫子的生活 解题报告 (种类并查集)

POJ 虫子的生活 解题报告

题目链接: http://dsalgo.openjudge.cn/tree/10/
思路:
这种涉及到多个类别(在这里的意思是产生过相互关系的虫子),和少量集合(这里指性别)的题目,我想到的是使用并查集,但是基础的并查集并不能解决这种问题,因为这里有两种类(类别和集合),应该使用升级版的种类并查集。
种类并查集的两个要点是:
1. 处理集合
2. 更新集合

我把实现细节放在了代码里:

#include <cstdio>

int Set[2010]; //并查集的父节点
int relaWithFarther[2010]; //记录与父节点的关系 0 same Sex, 1 diff Sex
bool suspicious;

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

int find(int node)
{
    if(Set[node] == node)
        return node;
    int end = find(Set[node]);
    relaWithFarther[node] = relaWithFarther[node] ^ relaWithFarther[Set[node]];
    //到这里node的父节点的父节点已经压缩到了end,node与end的关系可以由node与其现在的父节点的关系以及Set[node]与其父节点的关系推出来。
    Set[node] = end;
    return end;
}

void Union(int nodeA, int nodeB)
{
    int endA = find(nodeA);
    int endB = find(nodeB);
    //注意因为路径压缩,nodeA和nodeB的父节点已经转变。
    if(endA == endB)
    {
        if(relaWithFarther[nodeA] == relaWithFarther[nodeB])//同性
        {
            suspicious = true;
            return ;
        }
    }
    //此时保证了非同性
    Set[endA] = endB;
    relaWithFarther[endA] = relaWithFarther[nodeA] ^ relaWithFarther[nodeB] ^ 1;
    //同理推出更新规则
}

int main()
{
    int cases;
    int m, n;
    int nodeA, nodeB;
    scanf("%d", &cases);
    for(int t = 1; t <= cases; ++t) {
        ini();
        scanf("%d %d", &m, &n);
        for(int i = 0; i < n; ++i){
            scanf("%d %d", &nodeA, &nodeB);
            Union(nodeA, nodeB);
        }
        printf("Scenario #%d:\n", t);
        if(suspicious){
            printf("Suspicious bugs found!\n\n");
        }else{
            printf("No suspicious bugs found!\n\n");
        }
    }
    return 0;
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值