poj1182 食物链【带权并查集】
原创
©著作权归作者所有:来自51CTO博客作者Richie_LL的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目链接:http://poj.org/problem?id=1182
题意:中文题
解析:带权并查集,为每个元素创建三个元素,i-A,i-B,i-C,然后维护3*n个元素
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 1e6+100;
const int inf = 0x7fffffff;
int n,k;
int fa[maxn];
void init()
{
for(int i=0;i<=3*n;i++)
fa[i] = i;
}
int getfa(int x)
{
if(x==fa[x])
return x;
else
return fa[x] = getfa(fa[x]);
}
void merge(int u,int v)
{
int t1 = getfa(u);
int t2 = getfa(v);
if(t1!=t2)
fa[t1] = t2;
}
int main(void)
{
int ans = 0;
scanf("%d %d",&n,&k);
init();
for(int i=0;i<k;i++)
{
int t,x,y;
scanf("%d %d %d",&t,&x,&y);
if(x<1 || x>n || y<1 || y>n)
{
ans++;
continue;
}
int t1 = getfa(x);
int t2 = getfa(y+n);
int t3 = getfa(y+2*n);
if(t==1)
{
if(t1==t2 || t1==t3)
ans++;
else
{
merge(x,y);
merge(x+n,y+n);
merge(x+2*n,y+2*n);
}
}
else
{
t2 = getfa(y);
if(t1==t2 || t1==t3)
ans++;
else
{
merge(x,y+n);
merge(x+2*n,y);
merge(x+n,y+2*n);
}
}
}
printf("%d\n",ans);
return 0;
}