05-树8 File Transfer (25分)---并查集

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 NN (2\le N\le 10^42N104), the total number of computers in a network. Each computer in the network is then represented by a positive integer between 1 and NN. 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 c1and 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 kis 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
#define MAXSIZE 10001
using namespace std;

typedef int ElemType;


/*法1 查找元素在哪个集合,并返回集合的根
ElemType Find(ElemType s[],ElemType x){
	for(;s[x]>=0;x=s[x]) ;
	return x;
}*/
//法2 路径压缩 1找到根节if(s[x]<0) return x;else Find(s,s[x]),2将根节点变成x的父节点s[x]=Find(s,s[x]),3返回根return s[x] 
ElemType Find(ElemType s[],ElemType x){
	if(s[x]<0) return x;
	else 	return s[x]=Find(s,s[x]);
} 

//矮树贴在高树上,即按秩归并,最坏情况下树高=O(logN) 
void Union(ElemType s[],ElemType root1,ElemType root2){
	if(s[root1]集合2个数
		s[root1]+=s[root2]; 
		s[root2]=root1; 
	}else{
		s[root2]+=s[root1];
		s[root1]=root2;
	} 	
}


void Input(ElemType s[]){
	ElemType root1,root2;
	ElemType u,v;
	cin>>u>>v;
	root1=Find(s,u-1);//数组下标0开始,集合间1开始 
	root2=Find(s,v-1);
	if(root1!=root2) Union(s,root1,root2);
}

void CheckTwo(ElemType s[]){
	ElemType root1,root2;
	ElemType u,v;
	cin>>u>>v;
	root1=Find(s,u-1);
	root2=Find(s,v-1);	
	if(root1==root2) cout<<"yes"<>n;
	for(int i=0;i>in;
		switch(in){
			case 'I':Input(a);break;
			case 'C':CheckTwo(a);break;
			case 'S':CheckAll(a,n);break;
		}
		
	}while(in!='S'); 

	return 0;
}





你可能感兴趣的:(pta)