其他分享
首页 > 其他分享> > 1076 Forwards on Weibo

1076 Forwards on Weibo

作者:互联网

题目来源:PAT (Advanced Level) Practice

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 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.

words:

version 版本       Forwards 转发,向前       potential 潜在的       specific 具体的       indirect 间接的

题意:

给出有向图的n个结点可以到达它的点的信息以及层数 l ;求从某个点出发可以到达的点且路径数小于等于层数 l 点的个数

思路:

1. 根据题意创建邻接表表示有向图

2. 从要查询的某个点出发BFS访问其余点,在 l 层范围内统计可访问的点的个数即可

3. 本题也可使用DFS来做,但比较容易出错;

//PAT ad 1076 Forwards on Weibo 
#include <iostream>
using namespace std;
#include <set>
#include <vector>
#include <queue>
#define N 1005


int BFS(int x,vector<set<int> > &adj,int l)	//从点x开始BFS遍历,层数控制为l层 
{
	bool vis[N]={false};	//标记访问数组 
	queue<int> qe;
	qe.push(x);
	vis[x]=true;	//标记访问
	int count=0;	//可达的结点个数 
	int c=0;
	int n=qe.size();
	int level=0;	//当前层数 
	
	while(!qe.empty()&&level<l)
	{
		int x=qe.front();qe.pop();
		for(auto w:adj[x])
			if(vis[w]==false)
			{
				count++;		//统计邻接点的个数 
				qe.push(w);		
				vis[w]=true;	//标记访问
			}			
		c++;
		if(n==c)		//用于控制层数 
		{
			level++;
			n=qe.size();
			c=0;
		} 
	}
	return count;
}


int main()
{
	int n,l;
	cin>>n>>l;
	vector<set<int> > adj(n+1);	//邻接表 
	int i,m,x;
	for(i=1;i<=n;i++)	//输入并创建邻接表 
	{
		cin>>m;
		while(m--)
		{
			cin>>x;
			adj[x].insert(i);	//有向图 
		}
	} 
	int k;
	cin>>k;
	while(k--)
	{
		cin>>x;
		cout<<BFS(x,adj,l)<<endl;
	 } 
	
	
	
	return 0;
}

标签:Weibo,Forwards,1076,int,followers,user,qe,indirect
来源: https://blog.csdn.net/weixin_51032998/article/details/119052719