POJ1182

来源:互联网 发布:苹果手机照片导入mac 编辑:程序博客网 时间:2024/06/06 00:56

题目链接:

http://poj.org/problem?id=1182


题目大意:

动物王国中有三类动物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),输出假话的总数。


解题过程:

这题主要是看的书和博客,之前没接触过带权并查集。


题目分析:

这题用两种做法做了下,一种是挑战程序设计竞赛中的,另一种是搜的博客上面的。

首先说下简单粗暴的第一种方法:

一:

这里写图片描述

二:

对于每个节点有一个 Rank数组表示权值,这里引用两个blog好了:
http://blog.csdn.net/qq_24451605/article/details/46876121
http://blog.csdn.net/c0de4fun/article/details/7318642/


AC代码一:

#include<cstdio>using namespace std;const int MAX = 1123456;int N, K;int f[MAX];int root(int t) {    if (f[t] == t)        return t;    else        return f[t] = root(f[t]);}int connect(int a, int b) {    int fa = root(a);    int fb = root(b);    f[fa] = fb;}int same(int a, int b) {    return root(a) == root(b);}void init() {    for (int i = 0; i <= N*3; i++)        f[i] = i;}int main() {    int ans = 0;    scanf("%d %d", &N, &K);    init();    for (int i = 0; i < K; i++) {        int D, X, Y;        scanf("%d %d %d", &D, &X, &Y);        if (X > N || X < 1 || Y < 1 || Y > N) {            ans++;            continue;        }        else if (D == 1) {            if (same(X, Y+N) || same(X, Y+N*2)) {                ans++;                continue;            }            connect(X, Y);            connect(X+N, Y+N);            connect(X+N*2, Y+N*2);        }        else {            if (same(X, Y) || same(X, Y+N*2)) {                ans++;                continue;            }            connect(X, Y+N);            connect(X+N, Y+N*2);            connect(X+N*2, Y);        }    }    printf("%d\n", ans);}

AC代码二:

#include<cstdio>using namespace std;const int MAX = 112345;int ran[MAX], f[MAX];int N, K;void init() {    for (int i = 0; i <= N; i++)        f[i] = i, ran[i] = 0;}int root(int x) {    if (x == f[x])        return x;    int temp = f[x];    f[x] = root(f[x]);    ran[x] = (ran[x] + ran[temp])%3;    return f[x];}void connect(int a, int b, int type) {    int fa = root(a);    int fb = root(b);    if (fa == fb)        return;    f[fa] = fb;    ran[fa] = (type+ran[b]-ran[a]+3)%3;}bool check(int a, int b, int type) {    if (a > N || b > N)        return false;    if (type == 1 && a == b)        return false;    if (root(a) == root(b))        return (ran[a]-ran[b]+3)%3 == type;    else        return true;}int main() {    int ans = 0;    scanf("%d %d", &N, &K);    init();    while (K--) {        int D, X, Y;        scanf("%d %d %d", &D, &X, &Y);        D--;        if (check(X, Y, D))            connect(X, Y, D);        else            ans++;    }    printf("%d\n", ans);}
0 0
原创粉丝点击