AcWing 240. 食物链
动物王国中有三类动物 A,B,C这三类动物的食物链构成了有趣的环形。
A 吃 B,B 吃 C,C 吃 A。
现有 N 个动物,以 1∼N 编号。
每个动物都是 A,B,C 中的一种,但是我们并不知道它到底是哪一种。
有人用两种说法对这 N 个动物所构成的食物链关系进行描述:
第一种说法是 1 X Y
,表示 X 和 Y 是同类。
第二种说法是 2 X Y
,表示 X 吃 Y。
此人对 N 个动物,用上述两种说法,一句接一句地说出 K 句话,这 K 句话有的是真的,有的是假的。
当一句话满足下列三条之一时,这句话就是假话,否则就是真话。
- 当前的话与前面的某些真的话冲突,就是假话;
- 当前的话中 X 或 Y 比 N 大,就是假话;
- 当前的话表示 X 吃 X,就是假话。
你的任务是根据给定的 N 和 K 句话,输出假话的总数。
输入格式
第一行是两个整数 N 和 K,以一个空格分隔。
以下 K 行每行是三个正整数 D,X,Y两数之间用一个空格隔开,其中 D 表示说法的种类。
若 D=1,则表示 X 和 Y 是同类。
若 D=2,则表示 X 吃 Y。
输出格式
只有一个整数,表示假话的数目。
数据范围
1 ≤ N ≤ 5 4 , 0 ≤ K ≤ 1 0 5 1≤N≤5^4, 0≤K≤10^5 1≤N≤54,0≤K≤105
输入样例:
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
输出样例:
3
#include<bits/stdc++.h>
#include <unordered_map>
using namespace std;
template <typename T> void debug(string s, T x) { cout << s << "=" << x << "\n"; }
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pll;
typedef pair<int, int>pii;
const ll N = 2e5 + 5;
const ll MOD = 1e4;
const ll INF = 0x7fffffff;
int father[N];
int d[N], _size[N];
void init_set() {
for (int i = 1; i <= N; i++) {
father[i] = i;
_size[i] = 1;
}
}
int find_set(int x) {
if (x != father[x]) {
int root = find_set(father[x]);
d[x] += d[father[x]];
father[x] = root;
}
return father[x];
}
// void union_set(int x, int y) {
// x = find_set(x);
// y = find_set(y);
// //if(x!=y)s[x]=s[y];
// father[x] = y;
// d[x] = _size[y];
// _size[y] += _size[x];
// }
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, k;
cin >> n >> k;
init_set();
int ans = 0;
for (int i = 1; i <= k; i++){
int t, x, y;
cin >> t >> x >> y;
if (x > n || y > n) ans++;
else{
int px = find_set(x), py = find_set(y);
if (t == 1){
if (px == py && (d[x] - d[y]) % 3) ans++;
else if (px != py){
father[px] = py;
d[px] = d[y] - d[x];
}
}
else{
if (px == py && (d[x] - d[y] - 1) % 3) ans++;
else if (px != py){
father[px] = py;
d[px] = d[y] - d[x] + 1;
}
}
}
}
cout << ans;
return 0;
}