原题
点此链接1
题目分析
本题主要考察的是课本(高等教育出版社 - 陈越 - 《数据机构》)P159 4.6.3 集合及其运算。
按照课本中所述分析写出答案并不难。
个人Bug分析
如下图所述,现有两个集合:
- a - b - c
- d - e
按照输入的格式,如果有新的描述符 “I c e”,那么正确的结果如下图所示:
由于理解错误,本人写成了如下图所示的连接方式:
题目中有两个测试点就是测试这部分算法(按照“秩”的大小作连接,以减小寻找根节点的运算量),测试会无法通过,如下图所示:
代码
#include <iostream>
#include <vector>
using namespace std;
typedef pair<int, int> TPair;
typedef vector<int> Ints;
int Root(Ints &data, int index)
{
for (; data[index] >= 0; index = data[index])
;
return index;
}
int main()
{
// container store the data for process
int n;
cin >> n;
Ints data(n + 1, -1);
while (true)
{
// control charactor
char s = 0;
cin >> s;
if (s == 'S')
break;
// operation by the control charactor "s"
TPair tmpPair;
cin >> tmpPair.first >> tmpPair.second;
// operation insert
if (s == 'I')
{
/*
* first ... -> r1
* second ... -> r2
*/
auto r1 = Root(data, tmpPair.first);
auto r2 = Root(data, tmpPair.second);
// r1 is more longer: second ... -> r2 ---> r1
if (-data[r1] >= -data[r2])
{
data[r1] += data[r2];
data[r2] = r1;
}
// r2 is more longer: first ... -> r1 ---> r2
else
{
data[r2] += data[r1];
data[r1] = r2;
}
}
// operation check
else if (s == 'C')
{
if (Root(data, tmpPair.first) == Root(data, tmpPair.second))
cout << "yes" << endl;
else
cout << "no" << endl;
}
}
auto res = 0;
for (auto i = 1; i <= n;i++)
{
if (data[i] < 0)
++res;
}
if (res == 1)
cout << "The network is connected." << endl;
else
cout << "There are " << res << " components." << endl;
system("pause");
return 0;
}