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≤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. 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.
/*File Transfer */
/*思路:本题应该是涉及集合的问题,即两个电脑连接则属于同一个集合
根据二者元素是否在同一个集合中判断是否相连
根据集合中有几个子集合,即有几个组件
如果所有元素都在一个集合中,则全部相联*/
#include<stdio.h>
#include<stdlib.h>
void connect(int* array, int a, int b);
int find(int* array, int x);
void check(int* array, int a, int b);
int main() {
int N;/*节点个数*/
char laji;/*除去上一行的\n*/
scanf("%d", &N);
int* array = (int*)malloc((N + 1) * sizeof(int));
/*初始化*/
for (int i = 1; i < N + 1; i++) {
array[i] = -i;
}
char a;/*字符*/
int c1, c2;
while (1) {
scanf("%c", &laji);
scanf("%c", &a);
if (a == 'I') { /*用单引号*/
scanf("%d", &c1);
scanf("%d", &c2);
connect(array, c1, c2);
}
else if (a == 'C') {
scanf("%d", &c1);
scanf("%d", &c2);
check(array, c1, c2);
}
else break;
}
int cnt = 0;/*计数*/
for (int i = 1; i < N + 1; i++) { /*cnt为集合内子集合的个数*/
if (array[i] < 0) cnt++;
}
if (cnt == 1) printf("The network is connected.");
else printf("There are %d components.",cnt);
return 0;
}
void connect(int* array, int a, int b) { /*将较小元素作为根*/
a = find(array, a); /*找到它的根节点*/
b = find(array, b);
if (a < b) {
array[b] = a;
}
else {
array[a] = b;
}
}
int find(int* array, int x) { /*路径压缩*/
if(array[x]<0){
return x;
}
else{
return array[x]= find(array,array[x]);
}
}
/*不压缩
int find(int* array, int x) {
for (; array[x] > 0; x = array[x]);
return x;
}
*/
void check(int* array, int a, int b) {
a = find(array, a); /*找到它的根节点*/
b = find(array, b);
if (a == b) printf("yes\n");
else printf("no\n");
}