PAT甲级1076 Forwards on Weibo (30分)|C++实现

一、题目描述

原题链接
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:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

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

二、解题思路

给定起点,图的层序遍历题。注意题目这里给出的数据是一个用户follow的其他用户,而不是follow这个用户的人,所以在建立邻接表的时候,要注意一下。对于每个输入的query,我们进行一次层序遍历(用队列实现),将每个用户对应的层数存在level数组中,大于题目所要求的的L后,break即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 1010;
vector<vector<int> > Adj;
int main()
{
    
    
  int N, L, num, tmp, query;
  scanf("%d%d", &N, &L);
  Adj.resize(N+1);
  for(int i=1; i<=N; i++)
  {
    
    
    scanf("%d", &num);
    for(int j=0; j<num; j++)
    {
    
    
      scanf("%d", &tmp);
      Adj[tmp].push_back(i);
    }
  }
  scanf("%d", &num);
  for(int i=0; i<num; i++)
  {
    
    
    int cnt = 0, level[N+1];
    queue<int> q;
    bool inq[maxn] = {
    
    false};
    scanf("%d", &query);
    inq[query] = true;
    q.push(query);
    level[query] = 0;
    while(!q.empty())
    {
    
    
      tmp = q.front();
      q.pop();
      if(level[tmp] >= L)	break;
      for(int i=0; i<Adj[tmp].size(); i++)
      {
    
    
        if(!inq[Adj[tmp][i]])
        {
    
    
          q.push(Adj[tmp][i]);
          inq[Adj[tmp][i]] = true;
          level[Adj[tmp][i]] = level[tmp] + 1;
          cnt++;
        }
      }
    }
    printf("%d\n", cnt);
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108745295