PTA补题(10.29)

7-12 文件传输 (25分)

一开始用dfs来判断两点是否连通,就得了16分,剩下的样例都超时。后来改成并查集做的,第一次写的时候卡在了路径压缩,后来又多写了一点没多大用处的代码超时了…
ac的代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <map>
#include <queue>
#include <cmath>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#define ll long long
using namespace std;
const int maxn = 1e5+50;
int f[maxn];

void init()
{
    for(int i=1; i<=maxn; i++)
    {
        f[i] = i;
    }
}

int Find(int x)
{
    if(x!=f[x])
        f[x] = Find(f[x]);
    return f[x];
    //路径压缩另一种方法
   /* int r=x;
    while(f[r]!=r)
        r=f[r];
    int i=x,j;
    while(i!=r)
    {
        j=f[i];
        f[i]=r;
        i=j;
    }
    return r;
    */
}

void Union(int a,int b)
{
    int x = Find(a);
    int y = Find(b);
    if(x!=y)
        f[x] = f[y];
}

int main()
{
    ios::sync_with_stdio(false);
    int n,a,b;
    char t;
    init();
    cin>>n;
    while(true)
    {
        cin>>t;
        if(t=='S')
            break;
        else if(t=='I')
        {
            cin>>a>>b;
            Union(a,b);
        }
        else if(t=='C')
        {
            cin>>a>>b;
            if(Find(a)==Find(b))
                cout<<"yes"<<endl;
            else
                cout<<"no"<<endl;
        }
    }
    int cnt=0;
    for(int i=1; i<=n; i++)
    {
        if(f[i]==i)
        {
            cnt++;
        }
    }
    if(cnt==1)
        cout<<"The network is connected."<<endl;
    else
        cout<<"There are "<<cnt<<" components."<<endl;
    return 0;
}

并查集超时的代码
后来想了想,即使两节点具有相同的祖先,但是其f[i]不一定是其祖先的值,还可能是其父节点的值.所以条件f[a] == f[b]是错的

例如有4组数据: 每组先输入k(代表输入k个数),每组代表一个小圈子每组都与第一个节点相连.
3 10 1 2
2 3 4
4 1 5 7 8
2 4 10

执行完并查集代码之后,每个节点的情况是:(子节点: 父节点)
1: 10
2: 10
3: 3
4: 3
5: 10
6: 6
7: 10
8: 10
9: 9
10: 3
由此可以看出,1的父节点是10,10的父节点是3,所以并不是所有子节点都和祖宗节点相连.

	while(true)
    {
        cin>>t;
        if(t=='S')
            break;
        else if(t=='I')
        {
            cin>>a>>b;
            Union(a,b);
           for(int i=1; i<=n; i++)
               f[i] = Find(i);//这里一开始我是想让所有的点都与根节点相连,
               				//其实这一步就是多余的,多花了很多时间,当每次查询时直接Find ,看一看根节点相不相等就可以.
        }
        else if(t=='C')
        {
            cin>>a>>b;
            // if(Find(a)==Find(b))
            if(f[a]==f[b])
                cout<<"yes"<<endl;
            else
                cout<<"no"<<endl;
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值