LA 3644 简单并查集

题目大意:有一些简单的化合物,每个化合物由两种元素组成,把这些化合物按顺序装车,若k个化合物正好包含k种元素,那么就会爆炸。避免爆炸,有些化合物就不能装车。求有多少个不能装车。

题目分析:若k个化合物正好包含k种元素,那么就会爆炸。我们把每种元素看成一个顶点,每种化合物看成一条边,若有环存在的时候正好是爆炸的情况,所以避免成环记录不能放的数量就行了。

#include<iostream>
#include<cstdio>
using namespace std;

const int maxn=100010;
int f[maxn];

int findset(int x){ return f[x]==x?x:f[x]=findset(f[x]); }
int main()
{
    int x,y,i,remain;
    while(scanf("%d",&x) == 1)
    {
        remain=0;
        for(i=0;i<maxn;i++) f[i]=i;
        while(x!=-1)
        {
            scanf("%d",&y);
            x=findset(x);y=findset(y);
            if(x==y) remain++;
            else f[x]=y;
            scanf("%d",&x);
        }
        printf("%d
",remain);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiong-/p/3564958.html