Codeup 并查集之问题 B: 畅通工程

分析

我们可以把有道路能达到的两个城市看作一个连通块,那么题中要求的就是连通块的数量。
假设有n个连通块,那么只需要在两个连通块间建一条路就可以满足要求,因此最后输出n-1就是要求的答案

转换到并查集中就是集合数-1

#include<iostream>
using namespace std;
int father[1010];
bool isroot[1010];
int cnt;
void init()
{
    for(int i=1;i<1010;i++)
    {
        father[i]=i;
        isroot[i]=false;
    }
    cnt=0;
}
int findfather(int a)
{
    int b=a;
    while(a!=father[a])//找根
    {
        a=father[a];
    }
    //路径压缩
    while(b!=father[b])
    {
        int c=b;
        b=father[b];
        father[c]=a;
    }
    return a;
}
void Union(int a,int b)//合并集合
{
    int faa=findfather(a);
    int fab=findfather(b);
    if(faa!=fab)
    {
        father[faa]=fab;
    }
}
int main()
{
    int n,m;
    while(cin>>n)
    {
        if(n==0)break;
        cin>>m;
        init();
        int a,b;
        for(int i=0;i<m;i++)
        {
            cin>>a>>b;
            Union(a,b);
        }
        for(int i=1;i<=n;i++)//将根置为true
        {
            isroot[findfather(i)]=true;
        }
        for(int i=1;i<=n;i++)
        {
            if(isroot[i])cnt++;
        }
        cout<<cnt-1<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你遇到“git@codeup.aliyun.com: Permission denied (publickey)”这个错误信息时,通常意味着你的 Git 客户端无法使用预设的 SSH 密钥对验证远程服务器的身份,或者无法通过该密钥访问远程仓库。 以下是解决此问题的一些步骤: ### 1. 确认 SSH 密钥对的存在 确保你已经生成了有效的 SSH 密钥对,并将公钥添加到远程服务器的权限列表中。你可以通过以下几个命令检查并生成新的密钥对: ```bash # 检查当前目录下是否已经有 `.ssh` 目录及其中的公钥文件 ls .ssh/id_rsa.pub # 如果没有,生成一个新的密钥对 ssh-keygen -t rsa -b 4096 # 将公钥添加到远程服务器的权限列表中 cat ~/.ssh/id_rsa.pub | ssh user@example.com 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys' ``` ### 2. 清理本地配置 如果上述步骤无效,可能是由于本地 Git 配置的问题导致的。尝试清除或重新设置 SSH 的全局认证配置: ```bash rm ~/.ssh/config # 删除全局的 SSH 配置文件 ``` 然后重新设置连接: ```bash git config --global url."ssh://[username]@[hostname]:port/[repository_path]/".insteadOf "ssh://[username]@[hostname]/[repository_path]/" ``` ### 3. 重启 SSH 服务 在一些 Linux 发行版上,重启 SSH 服务可能会帮助解决问题: ```bash sudo systemctl restart sshd ``` ### 相关问题: 1. 如何确认本地已存在有效的SSH密钥? 2. 如果SSH密钥对未添加到远程服务器如何操作? 3. 当Git连接远程仓库时,除了“Permission denied (publickey)”之外还有哪些常见的错误提示及其解决方案是什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值