【POJ 1182 --- 食物链】种类并查集 || 思维+并查集
题目来源:点击进入【POJ 1182 — 食物链】
Description
动物王国中有三类动物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句话有的是真的,有的是假的。当一句话满足下列三条之一时,这句话就是假话,否则就是真话。
1) 当前的话与前面的某些真的话冲突,就是假话;
2) 当前的话中X或Y比N大,就是假话;
3) 当前的话表示X吃X,就是假话。
你的任务是根据给定的N(1 <= N <= 50,000)和K句话(0 <= K <= 100,000),输出假话的总数。
Input
第一行是两个整数N和K,以一个空格分隔。
以下K行每行是三个正整数 D,X,Y,两数之间用一个空格隔开,其中D表示说法的种类。
若D=1,则表示X和Y是同类。
若D=2,则表示X吃Y。
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
解题思路1
首先判断x,y是否超出范围,超出范围或者相等必定是错的。
将ABC三组分别用0—n-1,n—2n-1,2n—3n-1表示。
依次判断输入的d,x,y;
当d=1时:
只需判断x与y+n,x与y+2n是不是同类,如果是即是假话。如果不是即将x,y;x+n,y+n;x+2n,y+2n合并为一个。
当d=2时:
只需判断x与y,x与y+2n是不是同类,如果是即是假话。如果不是即将x,y+n;x+n,y+2n;x+2n,y合并为一个。
AC代码1:
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
const int MAXN = 5e4+5;
int pre[3*MAXN];
void init(int n)
{
for(int i=0;i<=3*n;i++)
pre[i]=i;
}
int _find(int x)
{
if(x==pre[x]) return x;
return pre[x]=_find(pre[x]);
}
void unite(int x,int y)
{
x=_find(x);
y=_find(y);
if(x!=y) pre[x]=y;
}
bool compare(int x,int y)
{
return _find(x)==_find(y);
}
int main()
{
SIS;
int n,m,a,b,d,ans=0;
scanf("%d%d",&n,&m);
init(n);
while(m--)
{
scanf("%d%d%d",&d,&a,&b);
if(a>n || b>n || (d==2&a==b)) ans++;
else if(d==1)
{
if(compare(a,b+n) ||compare(a,b+2*n)) ans++;
else
{
unite(a,b);
unite(a+n,b+n);
unite(a+2*n,b+2*n);
}
}
else
{
if(compare(a,b) || compare(a,b+2*n)) ans++;
else
{
unite(a,b+n);
unite(a+n,b+2*n);
unite(a+2*n,b);
}
}
}
cout << ans << endl;
return 0;
}
解题思路2
种类并查集,通过arr数组表示当前结点与父节点的关系。
假设x 吃 y, 那么x比y的权值大1.因为共有3种动物,那么权值要分为0,1,2三种。0是根结点, 如果有个节点的权值是1,就表示这个结点是吃根结点的,如果权值是2,表示2是吃1的(2比1大1),而因为三种动物循环吃的关系, 2 也就是被0吃的。
arr[x]==0:当前结点与父节点同类
arr[x]==1:当前结点吃父节点
arr[x]==2:父节点吃当前结点
通过合并和查找集合时更新arr数组。
AC代码2:
#include <iostream>
#include <cstdio>
using namespace std;
const int MAXN = 5e4+5;
int pre[MAXN],arr[MAXN];
int n,m,a,b,d,ans=0;
void init(int n)
{
for(int i=0;i<=n;i++)
pre[i]=i,arr[i]=0;
}
int _find(int x)
{
if(x==pre[x]) return x;
int p=pre[x];
pre[x]=_find(pre[x]);
arr[x]=(arr[p]+arr[x])%3;
return pre[x];
}
void unite()
{
int x=_find(a);
int y=_find(b);
pre[x]=y;
arr[x]=(arr[b]-arr[a]+d+2)%3;//d-1 + 3
}
bool compare()
{
if(a>n || b>n) return false;
else if(d==2 && a==b) return false;
int x=_find(a);
int y=_find(b);
if(x==y && (arr[a]-arr[b]+3)%3!=d-1) return false;
return true;
}
int main()
{
scanf("%d%d",&n,&m);
init(n);
while(m--)
{
scanf("%d%d%d",&d,&a,&b);
if(compare()) unite();
else ans++;
}
cout << ans << endl;
return 0;
}