PTA | 文件传输

当两台计算机双向连通的时候,文件是可以在两台机器间传输的。给定一套计算机网络,请你判断任意两台指定的计算机之间能否传输文件?

输入格式

首先在第一行给出网络中计算机的总数 n (2≤n≤1042≤n≤10^42n104),于是我们假设这些计算机从 1 到 n 编号。随后每行输入按以下格式给出:

I c1 c2  

其中I表示在计算机c1和c2之间加入连线,使它们连通;或者是

C c1 c2  

其中C表示查询计算机c1和c2之间能否传输文件;又或者是

S

这里S表示输入终止。

输出格式

对每个C开头的查询,如果c1和c2之间可以传输文件,就在一行中输出"yes",否则输出"no"。当读到终止符时,在一行中输出"The network is connected.“如果网络中所有计算机之间都能传输文件;或者输出"There are k components.”,其中k是网络中连通集的个数。

输入样例 1

5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S

输出样例 1

no
no
yes
There are 2 components.

输入样例 2

5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
I 1 3
C 1 5
S

输出样例 2

no
no
yes
yes
The network is connected.

思路

这道题是一个典型的并查集,因为它需要将两个连接计算机归入到同一个连通集里面。

在这道题里面有这样的阐述:

  1. I c1 c2表示在计算机c1和c2之间加入连线,需要union1(a, b);
  2. C c1 c2表示查询计算机c1和c2之间能否传输文件
    需要afa = find(a), bfa = find(b);if(afa == bfa) cout << "yes" << endl;
    实质上,就是检查这俩个是不是同一个父类。
  3. S结束连接。

Code

#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
int fa[30020];

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

int find(int i) {
	if(i == fa[i]) return i;
	else {
		fa[i] = find(fa[i]);
		return fa[i];
	}
}

int update(int i) {
	if(i == fa[i]) return i;
	else {
		fa[i] = find(fa[i]);
		return fa[i];
	}
}

void union1(int a, int b) {
	int afa = find(a), bfa = find(b);
	fa[afa] = bfa;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
    cin >> n;
	set<int> components;
	init(n);
	string s;
	while(cin >> s, s != "S") {
		char t = s[0];
		int a, b, afa, bfa;
		switch(t) {
		case 'I':
			cin >> a >> b;
			union1(a, b);
			break;
		case 'C':
			cin >> a >> b;
			afa = find(a), bfa = find(b);
			if(afa == bfa) cout << "yes" << endl;
			else cout << "no" << endl;
			break;
		}
	}
    for(int i = 1; i <= n; ++i) {
        update(i);
    }
    for(int i = 1; i <= n; ++i) {
        components.insert(components.end(), fa[i]);
    }
    if(components.size() == 1) cout << "The network is connected.";
	else cout << "There are " << components.size() << " components.";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mryan2005

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值