您的位置:首页 > 其它

POJ ~ 1182 ~ 食物链 (带权并查集)

2018-01-18 15:09 225 查看
参考博客:POJ-1182 食物链
思路:经典的带权并查集。除了并查集那个数组外,多开一个权值数组,或者把两个合成一个结构体数组。权值为每个点与根节点的关系//0:同类 1:吃 2:被吃。
图一:路径压缩 
图二:合并操作
图三:a和b相对关系



//#include<bits/stdc++.h>
#include<cstdio>
#include<iostream>
using namespace std;
const int MAXN = 50005;
int n, m, ans, f[MAXN], w[MAXN];//并查集数组和关系数组
//0:同类 1:吃 2:被吃
void init()
{
ans = 0;
for (int i = 0; i <= n; i++)
{
f[i] = i; w[i] = 0;
}
}
int Find(int x)
{
if (f[x] == x) return x;
int t = f[x];
f[x] = Find(f[x]);
w[x] = (w[x] + w[t]) % 3;
return f[x];
}
void Union(int a, int b, int D)
{
int root1 = Find(a), root2 = Find(b);
if (root1 != root2)
{
f[root1] = root2;
w[root1] = (w[b] + (D - 1) - w[a] + 3) % 3;
}
else
{
if ((w[a] - w[b] + 3) % 3 != D - 1) ans++;
}
}
int main()
{
//while(~scanf("%d%d", &n, &m))不知道为什么用多组输入输出会wa
scanf("%d%d", &n, &m);
{
init();//初始化
while (m--)
{
int D, x, y;
scanf("%d%d%d", &D, &x, &y);
if (x > n || y > n || (D == 2 && x == y)) { ans++; continue; }//大于N或者自己吃自己
Union(x, y, D);
}
printf("%d\n", ans);
}
return 0;
}
/*
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: