题目描述
动物王国中有三类动物 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,表示有 N 个动物,K 句话。
第二行开始每行一句话(按照题目要求,见样例)
输出格式
一行,一个整数,表示假话的总数。
输入样例
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
输出样例
3
说明
1 ≤ N ≤ 5 ∗ 10^4
1 ≤ K ≤ 10^5
题解
最暴力的做法就是开三倍空间的并查集,分别存每个动物的同类,天敌和猎物。
我们设动物$i$满足$1 leqslant i leqslant n$,那么他的猎物初始化为$i + n$,他的天敌初始化为$i + n + n$,其实这就相当于开$2n$个虚点,然后套并查集模板即可。

#include <iostream> #include <cstdio> #define MAX_N (50000 + 5) #define MAX_M (100000 + 5) using namespace std; int n, m; int r[MAX_N * 3]; int ans; int Root(int x) { int R = x, tmp; while(R != r[R]) R = r[R]; while(x != r[x]) tmp = r[x], r[x] = R, x = tmp; return R; } int main() { scanf("%d%d", &n, &m); for(register int i = 1; i <= n * 3; ++i) { r[i] = i; } int p, x, y; while(m--) { scanf("%d%d%d", &p, &x, &y); if(x > n || y > n || p == 2 && x == y) { ++ans; continue; } if(p == 1) { if(Root(x) == Root(y)) continue; if(Root(x + n) == Root(y) || Root(x + n + n) == Root(y)) { ++ans; continue; } r[Root(x)] = Root(y); r[Root(x + n)] = Root(y + n); r[Root(x + n + n)]= Root(y + n + n); } else { if(Root(x + n) == Root(y)) continue; if(Root(x) == Root(y) || Root(x + n + n) == Root(y)) { ++ans; continue; } r[Root(x)] = Root(y + n + n); r[Root(x + n)] = Root(y); r[Root(x + n + n)] = Root(y + n); } } printf("%d", ans); return 0; }
当然,用带权并查集也能做。我们把设$dis[i]$为动物$i$在其所在的食物链(并查集)中距离根节点的距离$mod 3$(因为只有$3$种动物)。
对于每一个说法,我们都可以判断所发中的动物$x$和动物$y$之间目前是否在同一条食物链(并查集),如果在,判断$dis[x]$和$dis[y]$是否满足说法中的关系即可。
如果不在同一个食物链(并查集),我们就合并他们即可,具体的操作可以看代码来理解。

#include <iostream> #include <cstdio> #define MAX_N (50000 + 5) #define MAX_M (100000 + 5) using namespace std; int n, m; int r[MAX_N], dis[MAX_N]; int ans; int Root(int x) { int tmp = r[x]; if(x != r[x]) { r[x] = Root(r[x]); dis[x] = (dis[x] + dis[tmp]) % 3; return r[x]; } return x; } int main() { scanf("%d%d", &n, &m); for(register int i = 1; i <= n; ++i) { r[i] = i; } int p, x, y; while(m--) { scanf("%d%d%d", &p, &x, &y); if(x > n || y > n || p == 2 && x == y) { ++ans; continue; } if(p == 1) { if(Root(x) == Root(y)) { if(dis[x] != dis[y]) ++ans; continue; } dis[r[x]] = (dis[y] - dis[x] + 3) % 3; r[r[x]] = r[y]; } else { if(Root(x) == Root(y)) { if(dis[x] != (dis[y] + 1) % 3) ++ans; continue; } dis[r[x]] = (dis[y] - dis[x] + 4) % 3; r[r[x]] = r[y]; } } printf("%d", ans); return 0; }