樹8 File Transfer

AllenRicard發表於2018-10-11

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.

答案如下:

#include <stdio.h>
#include <stdlib.h>
#define MAXN 10001
int FindRoot(int S[],int indix){
	int temp=indix;
	if(S[indix]<0) return indix;
  	else
  		for (;S[indix]>0;indix=S[indix]);
	S[temp]=indix;//路徑壓縮
	return indix;
}

void Union( int S[],int indix1,int indix2){
	int root1,root2;
	root1=FindRoot(S,indix1);
	root2=FindRoot(S,indix2);
	if(root1!=root2){
		/*保證小集合併入大集合*/
		if(S[root1]-S[root2]<=0){
			S[root2]+=S[root1];
			S[root1]=root2;
		}
		else{
			S[root1]+=S[root2];
			S[root2]=root1;
		}			
	}
}
void IsConnect(int S[],int indix1,int indix2){
	int root1,root2;
	root1=FindRoot(S,indix1);
	root2=FindRoot(S,indix2);
	if(root1!=root2)
		printf("no\n");
	else
		printf("yes\n");
}


	
int main(){
	int N,i,j,part=0;
	int S[MAXN];
	scanf("%d\n",&N);
	int k;
	for (k=1;k<=N;k++)
		S[k]=-1;
	char ch;
	scanf("%c",&ch);
	while(ch!='S'){
		if(ch=='I'){
			scanf("%d %d",&i,&j);
			getchar();
			Union(S,i,j);
		}
		else{
			scanf("%d %d",&i,&j);
			getchar();
			IsConnect(S,i,j);
		}
		scanf("%c",&ch);
	}
	for (k=1;k<=N;k++)
	{
		if(S[k]<0)
			part++;
		//printf("%d ",S[k]);
	}
	if(part==1)
		printf("The network is connected.");
	else
		printf("There are %d components.",part);
	return 0;
}

 

相關文章