7-5 文件传输 (25 分)

题目链接(可能已经无法提交了,只能看题面)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

并查集板子题,唯一有趣的地方就是判断是否所有网络都可以相互连接(即所有网络都在同一个集合内)

#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的个数就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值