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?
#include <iostream>
#include<cstdlib>
using namespace std;
#define MaxSize 10000
typedef int ElementType;
typedef int SetName;
typedef ElementType SetType[MaxSize];
void Initialization(SetType S, int N);
void Input_Connection(SetType S);
void Check_Connection(SetType S);
void Check_Network(SetType S, int N);
int main()
{
SetType S;
char in;
int N;
cin >> N;
Initialization(S, N);
do {
cin >> in;
switch (in) {
case 'I': Input_Connection(S); break;
case 'C': Check_Connection(S); break;
case 'S': Check_Network(S, N); break;
}
} while (in != 'S');
return 0;
}
//压缩路径
SetName Find(SetType S, ElementType X)
{
if (S[X] < 0) return X;
else return S[X] = Find(S, S[X]); //经过的所有节点挂到父节点上
}
//按规模归并
void Union(SetType S, SetName Root1, SetName Root2)
{
if (S[Root1] < S[Root2]) {
S[Root1] += S[Root2]; //根节点值为负的所有节点数
S[Root2] = Root1;
}
else {
S[Root2] += S[Root1];
S[Root1] = Root2;
}
}
//所有节点初始化为-1
void Initialization(SetType S, int N)
{
int i;
for (i = 0; i <= N; i++) {
S[i] = -1;
}
}
void Input_Connection(SetType S)
{
ElementType c1, c2;
SetName Root1, Root2;
cin >> c1 >> c2;
Root1 = Find(S, c1 - 1); //读写从1开始,数组从0开始
Root2 = Find(S, c2 - 1);
if (Root1 != Root2) { //不同根说明未连接
Union(S, Root1, Root2);
}
}
void Check_Connection(SetType S)
{
ElementType c1, c2;
SetName Root1, Root2;
cin >> c1 >> c2;
Root1 = Find(S, c1 - 1);
Root2 = Find(S, c2 - 1);
if (Root1 == Root2) { //同根,已连接
cout << "yes" << endl;
}
else {
cout << "no" << endl;
}
}
void Check_Network(SetType S, int N)
{
int cnt = 0, i;
for (i = 0; i < N; i++) {
if (S[i] < 0) cnt++; //检查根节点个数
}
if (cnt == 1) {
cout << "The network is connected." << endl;
}
else {
cout << "There are " << cnt << " components." << endl;
}
}