本专栏持续输出数据结构题目集,欢迎订阅。
题目
当两台计算机双向连通的时候,文件是可以在两台机器间传输的。给定一套计算机网络,请你判断任意两台指定的计算机之间能否传输文件?
输入格式:
首先在第一行给出网络中计算机的总数 n (2≤n≤10^4),于是我们假设这些计算机从 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.
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_N 10001 // 计算机编号从1到10^4
// 并查集结构,采用路径压缩和按秩合并优化
int parent[MAX_N];
int rank_[MAX_N]; // 使用rank_避免与关键字冲突
// 初始化并查集:每个节点的父节点是自身,秩为0
void init(int n) {
for (int i = 1; i <= n; i++) {
parent[i] = i;
rank_[i] = 0;
}
}
// 带路径压缩的查找操作
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // 路径压缩:直接指向根节点
}
return parent[x];
}
// 按秩合并操作
void unionSets(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) return; // 已在同一集合
// 秩小的集合合并到秩大的集合
if (rank_[rootX] < rank_[rootY]) {
parent[rootX] = rootY;
} else if (rank_[rootX] > rank_[rootY]) {
parent[rootY] = rootX;
} else {
// 秩相等时,合并后秩加1
parent[rootX] = rootY;
rank_[rootY]++;
}
}
// 统计连通分量的数量
int countComponents(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (parent[i] == i) { // 根节点数量即连通分量数
count++;
}
}
return count;
}
int main() {
int n;
scanf("%d", &n);
init(n);
char op;
while (1) {
scanf(" %c", &op); // 注意空格吸收前导空白
if (op == 'I') {
int c1, c2;
scanf("%d %d", &c1, &c2);
unionSets(c1, c2);
} else if (op == 'C') {
int c1, c2;
scanf("%d %d", &c1, &c2);
// 若根节点相同则连通
if (find(c1) == find(c2)) {
printf("yes\n");
} else {
printf("no\n");
}
} else if (op == 'S') {
break;
}
}
// 输出网络连通状态
int components = countComponents(n);
if (components == 1) {
printf("The network is connected.\n");
} else {
printf("There are %d components.\n", components);
}
return 0;
}
1377

被折叠的 条评论
为什么被折叠?



