05-樹9 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 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 N 10000
int check(int c1, int c2);
void connect(int c1, int c2);
void setunion(int root1, int root2);
int find(int x);
int a[N];

int main() {
	int i, n, c1, c2, count=0;
	char ch;
	scanf("%d", &n);
	for (i = 0;i < n;++i)
		a[i] = -1;
	while ((ch = getchar()) != 'S') {
		if (ch == 'I') {
			scanf("%d %d", &c1, &c2);
			connect(c1, c2);
		}
		else if (ch == 'C') {
			scanf("%d %d", &c1, &c2);
			if (check(c1, c2)) printf("yes\n");
			else printf("no\n");
		}
	}
	for (i = 0;i < n;++i) {
		if (a[i] < 0) count++;
	}
	if (count > 1) printf("There are %d components.\n", count);
	else printf("The network is connected.\n");
	return 0;
}

int check(int c1, int c2) {
	int root1, root2, result = 0;
	root1 = find(c1);
	root2 = find(c2);
	if (root1 == root2) result = 1;
	return result;
}

void connect(int c1, int c2) {
	int root1, root2;
	root1 = find(c1);
	root2 = find(c2);
	if (root1 != root2)
		setunion(root1, root2);
}

void setunion(int root1, int root2) {
	if (a[root1]< a[root2])
		a[root2] = root1;
	else {
		if (a[root1] == a[root2])
			a[root2]--;
		a[root1] = root2;		
	}
}

int find(int x) {
	if (a[x] < 0) return x;
	else return a[x] = find(a[x]);

}


發佈了35 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章