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 N N ( 2 ≤ N ≤ 1 0 4 2\le N\le 10^4 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 N N. Then in the following lines, the input is given in the format:
I c1 c2
where
I
stands for inputting a connection betweenc1
andc2
; orC c1 c2
where
C
stands for checking if it is possible to transfer files betweenc1
andc2
; orS
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 betweenc1
andc2
, 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 arek
components." wherek
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>#include <stdlib.h>#define maxSize 1000typedef int elementType;//元素的类型typedef int setName;//用根节点的下表作为集合的名称typedef elementType setType[maxSize];/*意思是setType 是 elementType[maxsize]的别名即 settype a 代表a是 elementype类型的具有maxsize个元素的数组*/setName find(setType S,elementType x){ for(;S[x]>=0;x=S[x])//找出根节点 printf(""); return x;}void Union(setType S,setName root1,setName root2){ S[root2]=root1;}void init(setType S,elementType n){ int i=0; for(i=0;i<n;i++) { S[i]=-1; }}void input(setType S){ elementType u,v; setName root1,root2; scanf("%d %d\n",&u,&v); root1=find(S,u-1); root2=find(S,v-1); printf("%d %d\n",root1,root2); if(root1!=root2) { Union(S,root1,root2); }}void check(setType S){ //printf("check"); elementType u,v; setName root1,root2; scanf("%d %d",&u,&v); root1=find(S,u-1); root2=find(S,v-1); //printf("%d %d",root1,root2); if(root1==root2) { printf("yes\n"); } else { printf("no\n"); }}void result(setType S,elementType n){ int i=0,counter=0; for(i=0;i<n;i++) { if(S[i]<0) counter++; } if(counter==1) printf("The network is conneted .\n"); else { printf("There are %d compents .\n",counter); }}int main(){ setType S; int n; char in; freopen("in.txt", "r", stdin); scanf("%d\n",&n); init(S,n); do { scanf("%c",&in); switch(in) { case 'I': input(S);break; case 'C': check(S);break; case 'S': result(S,n);break; } }while(in!='S'); return 0;}