PTA 파일 전송 (8 점) (데이터 구조) (C 언어)

17266 단어 PTA
(절강대학 교 데이터 구조) 제목: 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≤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:
네트워크 가 연결 되 어 있 습 니 다. 코드:
#include 
#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
"
) : printf("no
"
); } 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.
"
):printf("There are %d components.
"
,result); }

좋은 웹페이지 즐겨찾기