pat 1076

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] (≤) is the total number of people that user[i] follows; and user_list[i] is a list of the M[i] users that 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 trigger, 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

 

题意:给定一张图,给定k次查询,每次查询给定一个起始点,求从起始点开始的L层内包含的顶点数量(不包含起始点)。

思路:建图,这里我用的vector存储边(感觉二维数组可能会超时,读者可以自行尝试)。然后bfs遍历,遍历的时候用一个数组存储每个结点的层数layer,对于每一个结点i的邻接点,它的层数=layer[i]+1,当且仅当这个结点没有被遍历过,如果算出来的层数在L层内,将这个结点push到队列中,标记为已经访问过,否则仍让其处于未被访问的状态,因为可能从其他结点到这个结点计算层数的时候使得该结点的层数在L之内。

代码如下:

#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
vector<int> v[1005];
int n,l;
bool vis[1005]={false};
int layers[1005]={0};
void bfs(int s){
    fill(layers,layers+1004,0);
    fill(vis,vis+1004,false);
    int cnt=0;
    queue<int> q;
    q.push(s);
    vis[s]=true;
    while(!q.empty()){
        int temp=q.front();
        q.pop();
        for(int i=0;i<v[temp].size();i++){
            if(vis[v[temp][i]]==false)
                layers[v[temp][i]]=layers[temp]+1;
            if(layers[v[temp][i]]<=l&&vis[v[temp][i]]==false){
                vis[v[temp][i]]=true;
                q.push(v[temp][i]);
                cnt++;
            }
        }
    }
    printf("%d\n",cnt);
}
int main(){

    scanf("%d%d",&n,&l);
    int m,user;
    for(int i=1;i<=n;i++){
        scanf("%d",&m);
        for(int j=0;j<m;j++){
            scanf("%d",&user);
            v[user].push_back(i);
        }
    }
    int k;
    scanf("%d",&k);
    int s;
    for(int i=0;i<k;i++){
        scanf("%d",&s);
        bfs(s);
    }
    return 0;
} 

 

posted @ 2020-07-23 16:07  9761滴  阅读(108)  评论(0编辑  收藏  举报