数据结构 _ 基础练习 _ 7-8 File Transfer

原题

点此链接1

题目分析

本题主要考察的是课本(高等教育出版社 - 陈越 - 《数据机构》)P159 4.6.3 集合及其运算。
按照课本中所述分析写出答案并不难。

个人Bug分析

如下图所述,现有两个集合:

  1. a - b - c
  2. 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值