POJ 1182 食物链(分组解法)——及相同解法一道例题
此题是并查集的一道经典题目,解法并不唯一,此篇文章给出的是本题的分组解法,另外一种向量偏移解法会在我的同目录下的另一篇文章里给出,同样的,也会给出另一个例题。
题目链接:http://poj.org/problem?id=1182
题目大意是说,一共有三类物种,分别是A,B,C,它们互相制约形成一条食物链(环)。例如A吃B,B吃C,C吃A。现在,告诉你一共有n个动物,m个限制条件——形如d, x, y,当d = 1时,表示x和y属于同类物种(但并不知道是A,B,C的哪一种);当d = 2时,表示x可以吃y。
但是给你的m个条件中,有一部分是假话,假话的定义为,与之前的真话相矛盾,或者不符合题意(具体见题目描述)。
要求统计并输出假话的数目。
分组解法:因为题目中明确告诉了你组的数目,并且分组的数目相对较少(本题中为3组),对于这类并查集的题目,我们可以采取分组并查集的方法。即,将father数组的大小开至"组数*maxn"(本题就是father[3*50005]),其中,father[1~maxn]、father[maxn+1~2*maxn]、father[2*maxn+1~3*maxn],分别代表第一至三组。
那么对于题目给出的限制条件d,x,y:
当d = 1、x与y是同类的时候,若要检查其真假,我们需要检查find(x)与find(y+n)和find(y+2*n)是否为同类,如果是,则与条件矛盾,此话为假;反之,则证明x与y同类、x+n与y+n同类、x+2*n与y+2*n同类,我们可以将其对应并集起来。
当d = 2、x吃y,即x与y+n是同类,若要检查其真假,方法同上。
于是,我们可以有如下代码:
#include <iostream>
#include <cstdio>
using namespace std;
#define MAXN 200010
int n, m;
int father[MAXN];
int findset(int x) {
if(father[x] != x) {
father[x] = findset(father[x]);
}
return father[x];
}
void unionset(int x, int y) {
int a = findset(x), b = findset(y);
father[a] = b;
}
void init() {
for(int i = 0; i <= 3 * n; i++)
father[i] = i;
}
int main() {
scanf("%d%d", &n, &m);
int d, x, y;
init();
int ans = 0;
while(m--) {
scanf("%d%d%d", &d, &x, &y);
x--; y--;
if(d == 2 && x == y) {
ans++; continue;
} else if(x >= n || y >= n || x < 0 || y < 0) {
ans++; continue;
} if(d == 1) {
if(findset(x) == findset(y+n) || findset(x) == findset(y+2*n)) {
ans++; continue;
}
unionset(x, y);
unionset(x + n, y + n);
unionset(x + 2 * n, y + 2 * n);
} else {
if(findset(x) == findset(y) || findset(x) == findset(y+2*n)) {
ans++; continue;
}
unionset(x, y + n);
unionset(x + 2 * n, y);
unionset(x + n, y + 2 * n);
}
}
printf("%d\n", ans);
return 0;
}
相同解法的题目还有poj 1703黑帮与白帮问题
题目链接:http://poj.org/problem?id=1703
此题相对"食物链"来说更为简单,由于此题明确了一共只有两个帮派,所以father[2*maxn]即可,对于不同的两个帮派x和y而言,x+n与y和x与y+n即为一个相同帮派。
PS:需要注意的是,此题有个小trick,当n = 2时,由于要求两个帮派必须存在,所以不论查询什么,只要输出“In different gangs.”
AC代码:
<span style="font-size:18px;">#include <iostream>
#include <cstdio>
using namespace std;
#define MAXN 200010
int n, m;
int father[MAXN];
int findset(int x) {
if(father[x] != x) {
father[x] = findset(father[x]);
}
return father[x];
}
void unionset(int x, int y) {
int a = findset(x), b = findset(y);
father[a] = father[b] = father[x] = father[y] = min(a, b);
}
void init() {
for(int i = 0; i <= 2 * n; i++)
father[i] = i;
}
int main() {
int t;
scanf("%d", &t);
while(t--) {
scanf("%d%d", &n, &m);
int x, y;
char ch[5];
init();
while(m--) {
scanf("%s%d%d", ch, &x, &y);
x--; y--;
if(ch[0] == 'D') {
unionset(x, y+n);
unionset(y, x+n);
} else {
if(n == 2) {
puts("In different gangs."); continue;
}
int a = findset(x), b = findset(y), c = findset(y+n);
if(a == b) {
puts("In the same gang.");
} else if(a == c) {
puts("In different gangs.");
} else {
puts("Not sure yet.");
}
}
}
}
return 0;
}</span>

浙公网安备 33010602011771号