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
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值