2016年10月16日 星期日

(POJ) 1182-食物鏈

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

千萬不能寫while(cin>>n>>k) 或 while(scanf("%d %d",&n,&k) != EOF),這樣會WA,能處理一筆測資就好了!!!

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;

const int MAX_N = 5e4 + 5;

struct DisjointSet {
    int p[3*MAX_N+1];
    void init() {
        for (int x=0;3*MAX_N>=x;x++) {
            p[x]=x;
        }
    }
    int Find(int x) {
        return p[x]==x?x:p[x]=Find(p[x]);
    }
    void Union(int x,int y) {
        p[Find(x)] = Find(y);
    }
} djs;

int main () {
    int n,k;
    scanf("%d %d",&n,&k);
        int ans = 0;
        djs.init();
        while (k--) {
//            cout<<"ans = "<<ans<<endl;
            int a,b,c;
            scanf("%d %d %d",&a,&b,&c);
            if (b>n || c>n || b<=0 || c<=0) {
                ans++;
                continue;
            }
            if (a==2 && b==c) {
                ans++;
                continue;
            }
            if (a==1 && b!=c) {
                if (djs.Find(b) == djs.Find(c+MAX_N) || djs.Find(b+MAX_N) == djs.Find(c)) {
//                    cout<<"in1\n";
                    ans++;
                    continue;
                }
                else {
                    djs.Union(b,c);
                    djs.Union(b+MAX_N,c+MAX_N);
                    djs.Union(b+2*MAX_N,c+2*MAX_N);
                }
            }
            else if (a==2) {
                if (djs.Find(b) == djs.Find(c)) {
//                    cout<<"in3\n";
                    ans++;
                    continue;
                }
                else if (djs.Find(b+MAX_N) == djs.Find(c)) {
//                    cout<<"in2\n";
                    ans++;
                    continue;
                }
                else {
                    djs.Union(b,c+MAX_N);
                    djs.Union(b+MAX_N,c+2*MAX_N);
                    djs.Union(b+2*MAX_N,c);
                }
            }
        }
        printf("%d\n",ans);
    
}

沒有留言:

張貼留言