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.
//并查集
#include <iostream>
using namespace std;
//查找电脑c的根结点
int find(int computer[], int c){
//路径压缩
//cout << computer[c] << endl;
if(computer[c] < 0) return c;
else return computer[c] = find(computer, computer[c]);
}
//将c1和c2放入一个集合
void unionc(int computer[], int c1, int c2){
//依秩归并
int root1 = find(computer, c1);
int root2 = find(computer, c2);
if(computer[root1] < computer[root2]){
computer[root1] = computer[root1] + computer[root2];
computer[root2] = root1;
}else{
computer[root2] = computer[root1] + computer[root2];
computer[root1] = root2;
}
}
//检查c1和c2电脑的连通情况
void checkcomputer(int computer[], int c1, int c2){
int root1 = find(computer, c1);
int root2 = find(computer, c2);
//cout << root1 << " " << root2 << endl;
if(root1 == root2) cout << "yes" << endl;
else cout << "no" << endl;
}
//将c1和c2进行连接
void inputcomputer(int computer[], int c1, int c2){
unionc(computer, c1, c2);
}
//输出computer的连接情况
void printconnection(int computer[], int size){
int counter = 0;
for(int i = 1; i <= size; i++){
if(computer[i] < 0) counter++;
}
if(counter == 1) cout << "The network is connected.";
else cout << "There are " << counter << " components.";
}
int main()
{
char charin; //判断字符
int c1, c2;
int N; //总电脑数
cin >> N;
int computer[N + 1]; //记录电脑集合,下标从1开始,初始化-1
for(int i = 0; i <= N; i++){
computer[i] = -1;
}
do{
cin >> charin;
if(charin != 'S'){
cin >> c1 >> c2;
}
switch(charin){
case 'C':
checkcomputer(computer, c1, c2);
break;
case 'I':
inputcomputer(computer, c1, c2);
break;
case 'S':
printconnection(computer, N);
break;
}
}while(charin != 'S');
return 0;
}