Forwards on Weibo (30)

来源:互联网 发布:农村知客一般用词 编辑:程序博客网 时间:2024/05/24 03:43

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. 首先要考虑如何去建图,题中的第一组数据 (3 2 3 4)意思是 用户1有3个人关注(2,3,4),则建立从 2,3,4 到1 的有向边。
  2. 然后使用BFS或者DFS进行遍历,用DFS的话需要注意层次关系,即是要建立结构体
#include<bits/stdc++.h>using namespace std;const int maxn=1010;bool inq[maxn]={false};int n,l,num,val;struct node{   int level;   int v;};vector<node> G[maxn];int BFS(int u,int l){     int numforward=0;     queue<node> q;     node start;     start.v=u;     start.level=0;     q.push(start);     inq[start.v]=true;     while(!q.empty())     {         node top= q.front();         q.pop();         int s=top.v;         for(int i=0;i<G[s].size();i++)         {             node next=G[s][i];             next.level=top.level+1;             if(inq[next.v]==false && next.level<=l)             {                 q.push(next);                 inq[next.v]=true;                 numforward++;             }         }     }     return numforward;}int main(){   node temp;   scanf("%d%d",&n,&l);   for(int i=1;i<=n;i++)   {     temp.v=i;     scanf("%d",&num);    for(int j=0;j<num;j++)    {        scanf("%d",&val);        G[val].push_back(temp);    }   }   int num_query;   scanf("%d",&num_query);   for(int i=0;i<num_query;i++)   {      memset(inq,false,sizeof(inq));      scanf("%d",&val);      int numForward=BFS(val,l);      printf("%d\n",numForward);   }   return 0;}