PAT A1076 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 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

实现思路:

题意,微博用户发布微博后,他的粉丝便可以看见进行转发,同样转发者的粉丝也可以看见并转发,本题有分层的概念,并且统计第几层中所有的转发者数,有层的概念很容易联想到bfs,并且本题是无向图,所以在设置每个结点在第几层的时候,可能会重复设置,这就需要一个vist访问数组,当某一个结点设置过层数入队后,以后再遍历该结点的时候便不再入队。

AC代码:

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAXN=1010;
int N,L;
struct node {
	int high;
	vector<int> fans;
} Node[MAXN];
bool vist[MAXN];

int BFS(int x) {
	queue<int> q;
	Node[x].high=0;
	q.push(x);
	int ans=0;
	vist[x]=true;
	while(!q.empty()) {
		int id=q.front();
		ans++;
		q.pop();
		for(int i=0; i<Node[id].fans.size(); i++) {
			int cid=Node[id].fans[i];
			if(Node[id].high+1<=L&&!vist[cid]) {
				vist[cid]=true;//设置为已经入队过 
				Node[cid].high=Node[id].high+1;//设置当前入队结点的层数 
				q.push(cid);
			}
		}
	}
	return ans;
}

int main() {
	cin>>N>>L;
	int num,id;
	for(int i=1; i<=N; i++) {
		scanf("%d",&num);
		while(num--) {
			scanf("%d",&id);
			Node[id].fans.push_back(i);
		}
	}
	int m,queryId;
	cin>>m;
	while(m--) {
		fill(vist,vist+MAXN,0);
		scanf("%d",&queryId);
		cout<<BFS(queryId)-1<<endl;
	}
	return 0;
}
posted @ 2021-02-27 14:16  coderJ_ONE  阅读(48)  评论(0编辑  收藏  举报