(浙江大学数据结构)
题目:
File Transfer (8 分)
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≤104), 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.
代码:
#include<stdio.h>
#define MAXN 10000
int Find(int a[], int x);
void Union(int a[],int root1,int root2);
void I(int a[],int u,int v);
void C(int a[],int u,int v);
void S(int a[], int n);
int main()
{
int a[MAXN+1];
int n,i,j;
int u,v;
int fact=1;
char s;
scanf("%d",&n);
//初始化
for(i=1;i<=n;i++){
a[i]=-1;
}
while(fact){
getchar();//吃掉换行符
scanf("%c",&s);
if(s=='S'){
S(a,n);
fact=0;
}
else{
scanf("%d%d",&u,&v);
switch(s){
case 'I': I(a,u,v); break;
case 'C': C(a,u,v); break;
}
}
}
}
//此函数用于找到是s[x]的老祖宗
int Find(int a[], int x)
{
while(a[x]>=0){
x = a[x];
}
return x;
}
//此函数用于将s的两个根节点x1和x2连接起来,将较小的连接到较大的上面
void Union(int a[],int root1,int root2)
{
int x1,x2;
//当x1>=x2即1比2少时,将1接到2 ,否则将2接到1
x1 = a[root1]>=a[root2] ? root1:root2;
x2 = a[root1]>=a[root2] ? root2:root1;
a[x2] = a[x1]+a[x2];
a[x1] = x2;
}
void I(int a[],int u,int v)
{
int root1,root2;
root1 = Find(a,u);
root2 = Find(a,v);
if(root1!=root2){
Union(a,root1,root2);
}
}
void C(int a[],int u,int v)
{
Find(a,u)==Find(a,v) ? printf("yes\n") : printf("no\n");
}
void S(int a[], int n)
{
int i,result=0;
for(i=1;i<=n;i++){
if(a[i] < 0) result++;
}
result==1? printf("The network is connected.\n"):printf("There are %d components.\n",result);
}