P2024 [NOI2001] 食物链

原题链接

题解

关系具有矢量特性,因此可以带权并查集维护

code

#include<bits/stdc++.h>
#define ll long long
using namespace std;

int fa[50006];
int val[50006];
int finds(int now)
{
    if(now==fa[now]) return now;

    int tem=fa[now];

    fa[now]=finds(fa[now]);
    val[now]=(val[now]+val[tem])%3;

    return fa[now];
}


void solve()
{
    int n,k;
    cin>>n>>k;

    for(int i=1;i<=n;i++)
    {
        fa[i]=i;
        val[i]=0;
    }

    int ans=0;
    for(int i=1;i<=k;i++)
    {
        int op,x,y;

        cin>>op>>x>>y;

        if(x>n||y>n||op==2&&x==y)
        {
            ans++;
            continue;
        }
        if(op==1)
        {
            int fx=finds(x),fy=finds(y);
            if(fx==fy)
            {
                if(val[x]!=val[y]) ans++;
                continue;
            }
            int tem=val[x];
            fa[fx]=fy;
            val[fx]=(3-tem+val[y])%3;
        }
        else
        {
            int fx=finds(x),fy=finds(y);
            if(fx==fy)
            {
                if((val[x]-val[y]+3)%3!=1) ans++;
                continue;
            }
            int tem=val[x];
            fa[fx]=fy;
            val[fx]=(3-tem+val[y]+1)%3;
        }
    }

    cout<<ans;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    //cin>>t;
    while(t--) solve();
    return 0;
}


posted @   纯粹的  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示