1076. Forwards on Weibo (30)

1.该题需要采用合适的数据结构,本程序使用了用节点来进行存储,节点中有一个followers列表,记录了谁关注了该用户

2.使用层次遍历,直到最大level。

3.需要注意,用一个hasForwarded数组记录哪些用户已经转发,每个用户只转发一次。




AC代码:

//#include<string>
//#include <iomanip>
//#include<stack>
//#include<unordered_set>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<unordered_map>
#include<set>
#include<queue>
#include<map>
#include<vector>
#include <algorithm>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
#include<stack>
using namespace std;
struct UserNode{
	vector<int> follower;
	UserNode() :follower(0){};
};
int main(void)
{
	int userSum, maxLevel;
	cin >> userSum >> maxLevel;
	vector<UserNode> user(userSum);
	for (int i = 0; i < user.size(); i++)
	{
		int followSum;
		scanf("%d", &followSum);
		for (int j = 0; j < followSum; j++)
		{//用户i的关注列表
			int follow;
			scanf("%d", &follow);
			user[follow - 1].follower.push_back(i);
		}
	}

	int querySum;
	scanf("%d", &querySum);
	vector<int> query(querySum);
	for (int i = 0; i < query.size(); i++)
	{
		scanf("%d", &query[i]);
		query[i]--;//题目命名为1~N,但是程序命名为0~N-1
	}
	for (int i = 0; i < query.size(); i++)
	{//对每个查询的用户进行层次遍历
		queue<int> q;
		q.push(query[i]);
		int count1 = 1;
		int count2 = 0;
		int level = 0;
		int totalForward = 0;
		vector<bool> hasForwarded(userSum, false);
		hasForwarded[query[i]] = true;
		while (!q.empty()&&level<maxLevel)
		{
			for (int j = 0; j < count1; j++)
			{
				int head = q.front();
				q.pop();
				for (int k = 0; k < user[head].follower.size(); k++)
				{
					if (!hasForwarded[user[head].follower[k]])
					{//每个人只转发一次,还没转发的人进行转发
						hasForwarded[user[head].follower[k]] = true;
						q.push(user[head].follower[k]);
						count2++;
						totalForward++;
					}
				}
			}
			level++;
			count1 = count2;
			count2 = 0;
		}
		printf("%d\n", totalForward);
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值