Description
Input
Output
Sample Input
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
Sample Output
3
思路
关键点在于建立一个长度为3N的数组来存储动物,动物的猎物以及动物的天敌。i存动物,i+N存i的猎物,i+2N存i的天敌。
代码
#include <iostream>
using namespace std;
const int maxn = 500010;
int animal[maxn];
int height[maxn];
int N, K;
void initGroup(int num) {
for (int i = 1; i <= num; i++) {
animal[i] = i;
}
}
int findGroup(int x) {
if (x != animal[x]) {
animal[x] = findGroup(animal[x]);
}
return animal[x];
}
void unionGroup(int x, int y) {
x = findGroup(x);
y = findGroup(y);
if (x != y) {
animal[x] = y;
}
}
int main() {
int D, x, y;
//这里注意不要用while(scanf("%d%d", &N, &K)!=EOF)会报答案错误,另外也不要使用 cin来输入,会超时
scanf("%d%d", &N, &K);
//animal[i]表示同种族的 animal[i+N]存i吃的 animal[i+2*N]表示i被吃的
initGroup(N*3);
int ans = 0;
for (int i = 0; i < K; i++) {
scanf("%d%d%d", &D, &x, &y);
//cin >> D >> x >> y;
if (x > N || y > N || (x == y&&D==2)||x<=0||y<=0) {
ans += 1;
continue;
}
if (D == 1) {
if (findGroup(x) == findGroup(y + N) || findGroup(y) == findGroup(x + N)
|| findGroup(x) == findGroup(y + 2*N)|| findGroup(y) == findGroup(x + 2*N)) {
ans += 1;
continue;
}
//x,y是同种动物
else {
unionGroup(x, y);
unionGroup(x + N, y + N);
unionGroup(x + 2 * N, y + 2 * N);
}
}
else{
if (findGroup(x) == findGroup(y) || findGroup(x + 2 * N) == findGroup(y)) {
ans += 1;
continue;
}
//x吃y
else {
unionGroup(x + N, y);
unionGroup(x, y + 2 * N);
unionGroup(x + 2 * N, y + N);
}
}
}
cout << ans << endl;
return 0;
}
PS:对于不同的oj代码的细节部分需要改变,比如输入scanf()和输出部分,切记切记
原文:https://www.cnblogs.com/yyyxu/p/14616338.html