poj1182 并查集

题目http://poj.org/problem?id=1182

 

题目大意:动物分为三类 ABCAB BCCA。给出N个动物及动物之间的关系,判断哪些话是假的。

 

考查点:并查集

 

思路:首先要明白作为并查集,那么一颗树的含义是什么?并查集中主要记录的是每个点与他的父亲的关系(他的父亲是谁,他和父亲啥关系)。这个题也是在说动物间的关系,那么我们就不妨让两个点在同一棵树中表示这两个点的关系可以确定,节点和父亲的关系表示两个动物间的相对关系。

 

提交情况 Accepted 1

 

经验 并查集的本身结构就是

                            Struct NOED{

                                   Int father;

                                   Int relation;

}

 

一定要灵活的运用这两个信息。

 

收获 对并查集有了更深的认识, 一直以为并查集只是记录每个点的父亲是谁,没想到最初的并查集还是记录节点到根的距离的

 

AC code

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define MAXN 50001

 

struct NODE{

    int father;

    int relation;

};

NODE animal[MAXN];

 

void init(int n){

    for(int i = 0; i <= n; i ++){

       animal[i].father = i;

       animal[i].relation = 0;

    }

}

 

int find(int x){

    int temp;

    if(animal[x].father == x)

       return x;

    temp = animal[x].father;

    animal[x].father = find(animal[x].father);

    animal[x].relation = (animal[temp].relation + animal[x].relation) % 3;

    return animal[x].father;

}

 

void Union(int fx, int fy, int x, int y, int excursion){

    animal[fy].father = fx;

    animal[fy].relation = (animal[x].relation - animal[y].relation + 6 - excursion) % 3;

}

 

 

int main(){

    int t, d, x, y, fx, fy, ans = 0, n;

    scanf("%d %d", &n, &t);

    init(n);

    while(t --){

       scanf("%d %d %d", &d, &x, &y);

       if(x > n || y > n) ans ++;

       else

       if(d == 2 && x == y) ans ++;

       else{

           fx = find(x);

           fy = find(y);

           if(fx != fy)

              Union(fx, fy, x, y, d - 1);

           else

              if((animal[x].relation - animal[y].relation + 3) % 3 != d - 1) ans ++;

       }

    }

    printf("%d\n", ans);

    system("pause");

    return 0;

 

}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值