1076. Forwards on Weibo (30)
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.
Input Specification:
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.
Output Specification:
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.
Sample Input:
7 3
3 2 3 4
0
2 5 6
2 3 1
2 3 4
1 4
1 5
2 2 6
Sample Output:
4
5
结题思路:
题意要求我们找到确定起点和终点的最短路。
要求1:返回指定层数内的节点总数;
要求2:节点从一开始编号;
要求3:重复点不做计数。
程序步骤:
第一步、建立反向的链接表,节点保存parent的index信息;
第二步、层次遍历,直接判断访问情况即可,将没有访问过的入队,得到对应的节点总数即可。
具体程序(AC)如下:
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
int N,depth;
queue<int> q;
vector<int> map[1005];
bool visit[1005];//节点访问情况
int deep[1005];//存储节点深度
int countReach()//层次遍历
{
int tot=0;
int start,index;
while(!q.empty())
{
start=q.front();
q.pop();
for(int i=0;i<map[start].size();++i)
{
index=map[start][i];
if(!visit[index])
{
visit[index]=true;
deep[index]=deep[start]+1;
if(deep[index]>depth)//判断深度超过,立即返回
return tot;
++tot;
q.push(index);
}
}
}
return tot;
}
int main()
{
int i,j;
cin>>N>>depth;
for(i=1;i<=N;++i)
map[i].clear();
int num;
int child;
for(i=1;i<=N;++i)
{
cin>>num;
for(j=0;j<num;++j)
{
cin>>child;
map[child].push_back(i);
}
}
cin>>num;
int query;
for(i=0;i<num;++i)
{
cin>>query;
memset(visit,0,sizeof(visit));
memset(deep,0,sizeof(deep));
visit[query]=true;
while(!q.empty())
q.pop();
q.push(query);
//每次操作的预处理
cout<<countReach()<<endl;
}
return 0;
}