POJ 1182(并查集)

《挑战程序设计竞赛》,初级篇–树

// 并查集
#include <iostream>
#include <cstdio>
using namespace std;
#define maxn 50050

int p[maxn];
int N, K;
int d, x, y;
int ans = 0;

int find(int x)
{
    return p[x] == x ? x:p[x]=find(p[x]);
}

bool same(int x,int y)
{
    return find(x) == find(y);
}

void unite(int x,int y)
{
    x = find(x);
    y = find(y);
    if(x != y)
        p[x] = y;
}

void slove()
{
    for(int i = 1; i <= 3*N; i++)
        p[i] = i;
    while(K--)
    {
        cin>>d>>x>>y;
        if(x<0 || x>N || y<0 || y>N)
        {
            ans++;
            continue;
        }
        if(d == 1)
        {
            if(same(x,y+N) || same(x,y+2*N))
                ans++;
            else
            {
                unite(x,y);
                unite(x+N,y+N);
                unite(x+2*N,y+2*N);
            }
        }
        else
        {
            if(same(x,y) || same(x,y+2*N))
                ans++;
            else
            {
                unite(x,y+N);
                unite(x+N,y+2*N);
                unite(x+2*N,y);
            }
        }
    }
    printf("%d\n",ans);
}

int main()
{
    cin>>N>>K;
    slove();

    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
*/
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页