PTA 05-树8 File Transfer
题目链接
We have a network of computers and a list of bi-directional connections. Each of these connections allows a file transfer from one computer to another. Is it possible to send a file from any computer on the network to any other?
Input Specification:
Each input file contains one test case. For each test case, the first line contains N (2≤N≤10 ^4), the total number of computers in a network. Each computer in the network is then represented by a positive integer between 1 and N. Then in the following lines, the input is given in the format:
I c1 c2
where I stands for inputting a connection between c1 and c2; or
C c1 c2
where C stands for checking if it is possible to transfer files between c1 and c2; or
S
where S stands for stopping this case.
Output Specification:
For each C case, print in one line the word “yes” or “no” if it is possible or impossible to transfer files between c1 and c2, respectively. At the end of each case, print in one line “The network is connected.” if there is a path between any pair of computers; or “There are k components.” where k is the number of connected components in this network.
Sample Input 1:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S
Sample Output 1:
no
no
yes
There are 2 components.
Sample Input 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
Sample Output 2:
no
no
yes
yes
The network is connected.
程序框架
(陈越Mooc PPT)


按秩归并
(1)按树高

(2)按树的规模

路径压缩
沿路径递归将子节点全部直接挂到父节点上。

#include<iostream>
#define MaxSize 10010
using namespace std;
//在S中找有没有这个值->路径压缩
int Find(int S[],int u){
if(S[u]<0){
return u;
}else{
return S[u]=Find(S,S[u]);//路径压缩->递归
}
}
//按树的规模合并
void Union(int S[],int root1,int root2){
if(S[root1]<S[root2]){//abs S[root1] > abs S[root2];root1为大规模
S[root1]+=S[root2];//更新新的规模
S[root2]=root1;
}else{//规模一样大或root2为大规模
S[root2]+=S[root1];
S[root1]=root2;
}
}
//I
void Input(int S[]){
int u,v,root1,root2;
cin>>u>>v;//u存储在S[u-1]中,因为S从0开始的下标
root1=Find(S,u-1);
root2=Find(S,v-1);
if(root1!=root2){
Union(S,root1,root2);
}
}
//C
void Check(int S[]){
int u,v,root1,root2;
cin>>u>>v;
root1=Find(S,u-1);
root2=Find(S,v-1);
if(root1==root2){
printf("yes\n");
}else{
printf("no\n");
}
}
//S
void Check_netword(int S[],int N){
int count=0;
for(int i=0;i<N;i++){
if(S[i]<0){
count++;
}
}
if(count==1){
printf("The network is connected.\n");
}else{
printf("There are %d components.\n",count);
}
}
int main(){
int N;
cin>>N;
int S[N];
for(int i=0;i<N;i++){
S[i]=-1;//初始化全部为树根
}
char in;
do{
cin>>in;
switch(in){
case 'I':Input(S);break;
case 'C':Check(S);break;
case 'S':Check_netword(S,N);break;
}
}while(in!='S');
return 0;
}
本文探讨在一个双向连接的计算机网络中,如何判断是否可以从任意一台电脑传输文件到另一台,并分析了连接组件的数量。通过示例展示了路径压缩和按规模合并的方法。
804

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



