Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 72553 | Accepted: 21542 |
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
Source
问题链接:POJ1182 食物链。
题意简述:参见上文。
问题分析:(略)
程序说明:
原先写的程序逻辑过于繁琐。
重新写了一个程序,每个角色分成三身,分别是自己、被自己吃的和吃自己的。每一种关系都放入这三种身份中,判断就容易了。
题记:(略)
AC的C++语言程序如下:
/* POJ1182 食物链 */
#include
#include
using namespace std;
const int N = 50000;
int f[N * 3 + 1], cnt;
void UFInit(int n)
{
for(int i = 1; i <=n; i++)
f[i] = i;
cnt = n;
}
int Find(int a) {
return a == f[a] ? a : f[a] = Find(f[a]);
}
void Union(int a, int b)
{
a = Find(a);
b = Find(b);
if (a != b) {
f[a] = b;
cnt--;
}
}
int main()
{
int n, k, d, x, y, ans;
scanf("%d%d", &n, &k);
UFInit(n * 3);
ans = 0;
for(int i=1; i<=k; i++) {
scanf("%d%d%d", &d, &x, &y);
if(x > n || y > n || (d == 2 && x == y)) {
ans++;
continue;
}
if(d == 1) {
if(Find(n + x) == Find(y) || Find(n * 2 + x) == Find(y)) {
ans++;
continue;
}
Union(x, y);
Union(n + x, n + y);
Union(n * 2 + x, n * 2 + y);
} else if(d == 2) {
if(Find(x) == Find(y) || Find(n * 2 + x) == Find(y)) {
ans++;
continue;
}
Union(x, n * 2 + y);
Union(n + x, y);
Union(n * 2 + x, n + y);
}
}
printf("%d\n", ans);
return 0;
}
AC的C语言程序如下:
/* POJ1182 食物链 */
#include
#include
using namespace std;
const int N = 50000;
int relation[N+1]; //根点节到点节的关系
int parent[N+1];
void init(int n)
{
for(int i = 0; i <= n; ++i) {
parent[i]= i;
relation[i] = 0;
}
}
int find(int x)
{
if(x != parent[x]) {
int temp = parent[x];
parent[x] = find(temp);
relation[x] = (relation[x] + relation[temp]) % 3;
}
return parent[x];
}
int main()
{
int n, k, x, y, d, fx, fy, ans;
scanf("%d%d", &n, &k);
init(n);
ans = 0;
for(int i=0; i n || y > n || (d == 2 && x == y)) {
++ans;
continue;
}
fx = find(x);
fy = find(y);
if(fx == fy) {
if(d == 1 && relation[x] != relation[y])
++ans;
else if(d == 2 && relation[x] != (relation[y] + 2)%3)
++ans;
} else {
parent[fy] = fx;
relation[fy] = (relation[x] + (d - 1) + (3 - relation[y])) % 3;
}
}
printf("%d\n", ans);
return 0;
}