简单并查集题。题意:现在有一些都是只由两种元素组成的化合物,你把它们按顺序装进货车里。但是,考虑到一个安全隐患:如果车上有K个化合物(K大于2),这K个化合物刚好包含K种元素,那么它们就会组成一个易爆的混合物。为了安全起见,每当你拿到一个化合物准备装车时,你就要判断它是否会和已经装车的化合物构成易爆的混合物,如果是,那么这个化合物就不装车。请你最后输出有多少个化合物没有装车。
我的解题思路:K个化合物刚好包含K种元素且每个化合物只含有两种元素的情况下只能说明假设每个元素看成一个点,每个化合物看成一条边,那么这K个化合物刚好构成一个环,由K个点和K条边构成的环。所以判断一个化合物装车后会不会形成易爆混合物只需要判断会不会构成一个环即可。不用多说了,并查集解题。
我的解题代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <list>
using namespace std;
#define N 100001
int father[N];
int ans;
void Init();
int Find(int x);
void Union(int x, int y);
int main()
{
int a, b;
Init();
while (~scanf("%d", &a))
{
if (a == -1)
{
printf("%d\n", ans);
Init();
continue;
}
scanf("%d", &b);
if (Find(a) != Find(b)) Union(a, b);
else ans++;
}
return 0;
}
void Init()
{
ans = 0;
for (int i=0; i<N; ++i) father[i] = i;
return;
}
int Find(int x)
{
int z, y = father[x];
while (y != father[y])
{
y = father[y];
}
while (x != father[x])
{
z = father[x];
father[x] = y;
x = z;
}
return y;
}
void Union(int x, int y)
{
int fx = Find(x);
int fy = Find(y);
father[fx] = fy;
return;
}