zoukankan      html  css  js  c++  java
  • POJ1182 食物链 并查集

    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
    const int N = 100005;
    int r[N], father[N];//定义一个关系数组,定义一个父亲(路径)数组;
    int Find(int x);//寻找根节点,并且找这个点与根节点的关系
    int main()
    {
    int amount, sentence, relation, a, b, ans;
    ans=0;
    scanf("%d%d", &amount, &sentence);
    for(int i=0; i<=amount; i++)//初始化,每个点的父节点都是他自己,每个店与自己的关系都是0同类
    {
    father[i]=i;
    r[i]=0;
    }
    while(sentence--)//说了几句话
    {
    scanf("%d%d%d", &relation, &a, &b);
    int ra=Find(a);//找根节点
    int rb=Find(b);//找根节点
    //注意这里是if-else if语句不是,if-else语句
    if(a>amount||b>amount||a<=0||b<=0||(relation==2&&a==b))
    ans++;//越界或者关系是捕食但a和b相等是同类
    else if(ra==rb&&(relation-1+r[b])%3!=r[a])
    ans++;//若根节点相同,但是到根节点的关系不同,
    else if(ra!=rb)//若根节点不同
    {
    father[ra]=rb;//合并两个集合,路径压缩
    r[ra]=((relation-1)-r[a]+r[b]+3)%3;//关系压缩
    }
    }
    printf("%d ", ans);
    return 0;
    }
    int Find(int x)
    {
    int k=father[x];
    if(father[x]!=x)
    {
    father[x]=Find(father[x]);
    r[x]=(r[k]+r[x])%3;
    }
    return father[x];
    }

  • 相关阅读:
    Proof of Stake-股权证明 系列3
    共识算法的比较:Casper vs Tendermint
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
  • 原文地址:https://www.cnblogs.com/wazqWAZQ1/p/4667613.html
Copyright © 2011-2022 走看看