数据结构 _ PAT练习 _ 1076 Forwards on Weibo

PTA 1076 Forwards on Weibo

原题

点此链接1

程序

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

vector<vector<int>> followers;	// indicate the followers of i
int N = 0; // number of people
int L = 0; // max direct layers

int bfs(int user, int level_thre)
{
	vector<int> level(N + 1); // 0: have not visited or user himself/herself

	queue<int> q;
	q.push(user);
	int res = 0;
	while (!q.empty())
	{
		auto u = q.front();
		q.pop();
		auto now_level = level[u];

		// if get the threhold, continue
		if (now_level == level_thre)
			continue;

		for (const auto&r : followers[u])
		{
			// if have been visited
			if (level[r] || r == user)
				continue;

			level[r] = now_level + 1;
			q.push(r);

			// every push means that a new follow message
			res++;
		}
	}
	return res;
}

int main()
{
	cin >> N >> L;

	// warning! 0 is not a human!
	followers.resize(N + 1);
	
	for (auto i = 1; i <= N; i++)
	{
		int all;
		cin >> all;
		for (auto j = 0; j < all; j++)
		{
			int follows; // 这表示i关注了谁
			cin >> follows;
			followers[follows].push_back(i);
		}
	}

	vector<int> test; // test users
	{
		int all;
		cin >> all;
		for (auto j = 0; j < all; j++)
		{
			int user;
			cin >> user;
			test.push_back(user);
		}
	}

	for (const auto&r : test)
		cout << bfs(r, L) << endl;
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值