运行结果
我的代码
#include<iostream>
using namespace std;
typedef int SetName;
typedef int Element;
typedef int* SetType;
typedef int ElementType;
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 (Root1 == Root2 || S[Root1] >= 0 || S[Root2] >= 0)
return;
if (S[Root1] < S[Root2]) {
S[Root2] += S[Root1];
S[Root1] = Root2;
}
else {
S[Root1] += S[Root2];
S[Root2] = Root1;
}
}
void IsSameSet(SetType S)
{
Element C1, C2;
cin >> C1 >> C2;
--C1; --C2;
if (Find(S, C1) == Find(S, C2))
cout << "yes" << endl;
else
cout << "no" << endl;
}
void NumOfSet(SetType S, int N)
{
int cnt{ 0 };
for (int i = 0; i < N; ++i) {
if (S[i] < 0)
++cnt;
}
if (cnt == 1)
cout << "The network is connected.";
else
cout << "There are " << cnt << " components.";
}
void Connect(SetType S)
{
Element E1, E2;
cin >> E1 >> E2;
--E1; --E2;
Union(S, Find(S, E1), Find(S, E2));
}
int main()
{
int N;
cin >> N;
int* arr;
arr = new int[N];
for (int i = 0; i < N; ++i) {
arr[i] = -1;
}
char a;
bool flag{ true };
while (cin >> a && flag ==true) {
switch (a) {
case 'C':
IsSameSet(arr);
break;
case 'I':
Connect(arr);
break;
case 'S':
NumOfSet(arr, N);
flag = false;
break;
default:
break;
}
}
delete[] arr;
return 0;
}
|