/* 返回顶部 */

# Luogu P2024 [NOI2001] 食物链

gate

$d[x]-d[y]=0$$x,y$是同类
$d[x]-d[y]=1$$x$$y$
$d[x]-d[y]=2$$x$$y$$(mod\ 3)$

$x,y$的父节点为$fx,fy$
$fx$$fy$的距离为$fx \rightarrow x \rightarrow y \rightarrow fy$

f[fx] = fy;
d[fx] = (d[y]-d[x]+1+3)%3;


$d[x] = d[x]+d[fa[x]]$

int getfa(int x) {
if(fa[x] == x)return x;
int t = fa[x];
fa[x] = getfa(fa[x]);
d[x] = (d[x]+d[t])%3;
return fa[x];
}


$code$

#include<cstdio>
using namespace std;

const int maxn = 100005;
int n,k,a,x,y,cnt;
int fa[maxn],d[maxn];

int getfa(int x) {
if(fa[x] == x)return x;
int t = fa[x];
fa[x] = getfa(fa[x]);
d[x] = (d[x]+d[t])%3;
return fa[x];
}

int main() {
scanf("%d%d",&n,&k);
for(int i = 1; i <= n; i++) {
fa[i] = i;
d[x] = 0;
}
while(k--) {
scanf("%d%d%d",&a,&x,&y);
if(x>n || y>n ||(a==2&&x==y)) {
cnt++;
continue;
}
int xx = getfa(x);
int yy = getfa(y);
if(a == 1) {
if(xx != yy) {
fa[xx] = yy;
d[xx] = (d[y]-d[x]+3)%3;
continue;
} else if((d[x]-d[y]+3)%3!=0)cnt++;
}
if(a == 2) {
if(xx != yy) {
fa[xx] = yy;
d[xx] = (d[y]-d[x]+1+3)%3;
continue;
} else if((d[x]-d[y]+3)%3!=1)cnt++;
}
}
printf("%d",cnt);
return 0;
}

posted @ 2021-10-27 09:08  Mogeko  阅读(62)  评论(0编辑  收藏  举报