题目链接(可能已经无法提交了,只能看题面)
并查集板子题,唯一有趣的地方就是判断是否所有网络都可以相互连接(即所有网络都在同一个集合内)
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int N = 1e4 + 10;
int f[N];
int findn(int x)
{
if (x == f[x])
return x;
else
return f[x] = findn(f[x]);
}
int main(int argc, char const *argv[])
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)//初始化
f[i] = i;
while (1)
{
int x, y;
string s;
cin >> s;
if (s == "S")
break;
else if (s == "C")
{
cin >> x >> y;
if (findn(x) == findn(y))
printf("yes\n");
else
printf("no\n");
}
else if (s == "I")
{
cin >> x >> y;
if (findn(x) != findn(y))
f[findn(y)] = findn(x);
}
}
int sum = 0;
for (int i = 1; i <= n; i++)
if (f[i] == i)
sum++;
if (sum == 1)
printf("The network is connected.\n");
else
printf("There are %d components.\n", sum);
return 0;
}
并查集操作完成之后,需要判断有几个不相交的集合的时候我们可以找f[i]=i
的个数,它的个数就是不相交集合的个数。
原因是如果f[i]=i
的话就代表i这个点是某个集合的祖宗节点,祖宗节点有几个那么不相交的集合就有几个,哪怕我们最后没更新每个点的祖宗节点,例如if (findn(x) != findn(y)) f[findn(y)] = findn(x);
在这个代码中,我们只是把y的祖宗节点设置为x,那么y的“小弟”们其实并没有更新到x,也就是说y的“小弟”们的祖宗节点仍然是y。
例如在样例中,虽然最后一行我们把1的祖宗节点设置为4,但是2和3的祖宗节点仍然是1,并没有随着1的更新而更新,但是这并不影响我们统计最后的集合个数,因为我们只需要看f[i]=i
的个数就可以了