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;
}