W4 - The Suspects(POJ - 1611)

题目描述

在这里插入图片描述

Input & Output

在这里插入图片描述

Sample

在这里插入图片描述

Code

/*
 * @Description: The Suspects
 * @version:
 * @Author:
 * @Date: 2021-04-21 18:27:35
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-04-21 22:21:02
 */
// self
// 提交三次,逻辑问题
#include <iostream>
#include <vector>
using namespace std;
int Find(int a, vector<int> &father)
{
	if (father[a] == a)
		return a;
	else
		return father[a] = Find(father[a], father);
}
void Merge(int a, int b, vector<int> &father)
{
	int fa = Find(a, father);
	int fb = Find(b, father);
	if(fa != fb)
		father[fa] = fb;
}
int main()
{
	int num_student, num_group;
	while (cin >> num_student >> num_group && (num_student || num_group))
	{
		vector<int> father(num_student, -1);
		while (num_group--)
		{
			int num;
			cin >> num;
			int first;
			for (int i = 0; i < num; i++)
			{
				int current;
				cin >> current;
                // 对第一个结点进行特殊操作
				if (i == 0)
				{
                    // 若该组的第一个结点之前没有进入集合,则初始化为他自己,并保存他自己为first
					if (father[current] == -1)
					{
						first = current;
						father[current] = current;
					}
					else
					{
                        // 否则,保存第一个结点的父亲为first
						first = father[current];
					}
				}
                // 若后面的结点没有出现过,则初始化为首节点的父亲
				else if (father[current] == -1)
					father[current] = father[first];
                // 若这个结点之前出现过,则把两个父亲合并
				else
					Merge(current, first, father);
			}
		}
		// 更新所有节点的根节点
		for (int i = 0; i < num_student; i++)
		{
            // 只更新出现的结点,否则出异常
			if (father[i] != -1)
				father[i] = Find(i, father);
		}
		unsigned sum = 0U;
		if (father[0] == -1)
		{
            // 说明0没有和任何同学接触,则只有他自己
			cout << 1 << endl;
			continue;
		}
		for (vector<int>::iterator it = father.begin(); it != father.end(); ++it)
		{
            // 找出现的结点中与0号结点父亲一样(同一集合中),则与传染者有接触
			if (*it == father[0])
				sum++;
		}
		cout << sum << endl;
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jian圣楠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值