LA - 3644 - X-Plosives

题意:一些产品,每种产品由2种化合物合成,按顺序接收一些产品,若组成其中某些产品的化合物的种类数与这些产品的产品数相等,就要拒绝接收,因为可能爆炸,求要拒绝多少次。

题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=19&page=show_problem&problem=1645

——>>若加入的化合物与已存在的化合物构成了环,就该拒绝,用并查集解决即可。

#include <iostream>

using namespace std;

const int maxn = 100000 + 10;

int fa[maxn], height[maxn];     //并查集的父亲数组与树的高度数组

int find(int x)     //并查集找根函数
{
    return (fa[x] != x) ? find(fa[x]) : x;
}

bool judge(int x, int y)        //并查集联合函数
{
    int new_x = find(x);
    int new_y = find(y);
    if(new_x == new_y) return 0;
    if(height[new_x] > height[new_y])       //当树 new_x 比树 new_y 高时
        fa[new_y] = new_x;
    else if(height[new_x] == height[new_y])     //当树 new_x 和树 new_y 一样高时
    {
        fa[new_y] = new_x;
        height[new_x]++;
    }
    else
        fa[new_x] = new_y;      //当树 new_y 比树 new_x 高时
    return 1;
}

int main()
{
    int a, b, i;
    while(cin>>a)
    {
        for(i = 0; i < maxn; i++)       //并查集初始化
        {
            fa[i] = i;      //第个点自成一棵树
            height[i] = 1;      //只有自己,高度为1
        }
        int refuse_cnt = 0;
        while(a != -1)
        {
            cin>>b;
            if(judge(a, b) == 0) refuse_cnt++;      //如果存在环的话,拒绝数+1
            cin>>a;
        }
        cout<<refuse_cnt<<endl;
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值