链接:https://www.nowcoder.com/questionTerminal/920f0f6ad2b94d44b929e2d7f0afdc80
来源:牛客网
Weibo is known as the Chinese version of Twitter. One user on Weibo may have many followers, and may follow many other users as well. Hence a social network is formed with followers relations. When a user makes a post on Weibo, all his/her followers can view and forward his/her post, which can then be forwarded again by their followers. Now given a social network, you are supposed to calculate the maximum potential amount of forwards for any specific user, assuming that only L levels of indirect followers are counted.
输入描述:
Each input file contains one test case. For each case, the first line contains 2 positive integers: N (<=1000), the number of users; and L (<=6), the number of levels of indirect followers that are counted. Hence it is assumed that all the users are numbered from 1 to N. Then N lines follow, each in the format: M[i] user_list[i] where M[i] (<=100) is the total number of people that user[i] follows; and user_list[i] is a list of the M[i] users that are followed by user[i]. It is guaranteed that no one can follow oneself. All the numbers are separated by a space. Then finally a positive K is given, followed by K UserID's for query.
输出描述:
For each UserID, you are supposed to print in one line the maximum potential amount of forwards this user can triger, assuming that everyone who can view the initial post will forward it once, and that only L levels of indirect followers are counted.
示例1:
输入
7 3 3 2 3 4 0 2 5 6 2 3 1 2 3 4 1 4 1 5 2 2 6
输出
4 5
题意就是给出n个用户,每个用户的关注列表,例如第一个人关注了2 3 4,第二个人没关注,第三个人关注了5 6,以此类推,最后一行问2个人发一条微博可能被转发的最大次数,假设每个粉丝都会转发,在深度为L内的粉丝的粉丝也会转发。例如问2时,1是2的粉丝会转发,4是1的粉丝又会转发,5和6又是4的粉丝又会转发,所以在深度为3的情况下最多被转发4次。
看到题目时深度限制就想到BFS了,不过当时又想反正所有点都是要遍历一遍的,DFS的话代码会短一点吧,然后做完看了别人的代码果然DFS代码短一点,但是时间上感觉差不多了,因为BFS的话就能直接开写了,DFS特判还想了一会会=。=
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
int n,l;
vector<int> edge[1005];
int vis[1005];
void dfs(int index,int deep,int &ans)
{
for(int i=0;i<edge[index].size();i++)
{
if(deep+1<=l&&(deep+1<vis[edge[index][i]]||vis[edge[index][i]]==-1))//深搜的话要判断第二次进入时深度是不是更小
{
if(vis[edge[index][i]]==-1)//第一次访问时才自增点数答案
ans++;
vis[edge[index][i]]=deep+1;
dfs(edge[index][i],deep+1,ans);
}
}
}
int main()
{
scanf("%d %d",&n,&l);
for(int i=1;i<=n;i++)
{
int m;
scanf("%d",&m);
for(int j=0;j<m;j++)
{
int user;
scanf("%d",&user);
edge[user].push_back(i);
}
}
int k;
scanf("%d",&k);
for(int i=0;i<k;i++)
{
memset(vis,-1,sizeof(int)*1005);//每次询问初始化数组和答案数
int user,ans=0;
scanf("%d",&user);
vis[user]=2000;
dfs(user,0,ans);
printf("%d\n",ans);
}
return 0;
}