AcWing 240. 食物链
原题链接
中等
作者:
Value
,
2020-06-22 19:20:57
,
所有人可见
,
阅读 389
#include <iostream>
using namespace std;
const int N = 50010;
int parent[N], dis[N];
void init(){
for(int i = 0; i < N; i ++ ) parent[i] = i;
}
int find(int x){
if(parent[x] == x) return x;
int u = find(parent[x]);
dis[x] += dis[parent[x]];
parent[x] = u;
return u;
}
int main(){
init();
int n, k;
cin >> n >> k;
int t, a, b;
int res = 0;
while(k -- ){
cin >> t >> a >> b;
if(a > n || b > n){
res ++ ;
continue;
}
int pa = find(a);
int pb = find(b);
if(t == 1){
if(pa == pb){
if((dis[a] - dis[b]) % 3) res ++ ;
}else{
parent[pa] = pb;
dis[pa] = dis[b] - dis[a];
}
}else{
if(pa == pb){
if((dis[a] - dis[b] - 1) % 3) res ++ ;
}else{
parent[pa] = pb;
dis[pa] = dis[b] + 1 - dis[a];
}
}
}
cout << res << endl;
return 0;
}