食物链 (带边权并查集)

[亡魂溺海] 提交于 2020-01-14 20:03:36

题目链接

题意:中文题面,无过多客套话,就不说了

思路:参考:https://blog.csdn.net/ccsu_cat/article/details/78089233

把父节点与子节点的关系用向量表示,一共有三种关系,

0代表同类;1代表被根节点吃;2代表吃根节点。

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

const int maxn = 5e4+100;
struct node
{
    int p;
    int relation;
}node[maxn];

void init(int n)
{
    for(int i=1;i<=n;i++)
    {
        node[i].p = i;
        node[i].relation = 0;
    }
}

int find(int x)
{
    if(x == node[x].p)return x;
    int tmp = node[x].p;
    node[x].p = find(tmp);
    node[x].relation = (-node[tmp].relation + node[x].relation + 3)%3;
    return node[x].p;
}
int main()
{
    int n,m,op,u,v;
    int ans = 0;
    scanf("%d%d",&n,&m);
    init(n);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&op,&u,&v);
        if(u > n || v > n)
        {
            ++ans;
            continue;
        }
        if(op == 2 && u == v)
        {
            ++ans;
            continue;
        }
        int rt1,rt2;
        rt1 = find(u);
        rt2 = find(v);
        if(rt1 == rt2)
        {
            if(op == 1 && node[u].relation != node[v].relation)++ans;
            if(op == 2 && ( -node[u].relation + node[v].relation + 3)%3 != op - 1)++ans;
        }
        else
        {
            node[rt2].p = rt1;
            node[rt2].relation = (-node[u].relation + op - 1 + node[v].relation + 3)%3;
        }
    }
    cout<<ans<<'\n';
}

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!