PAT A1076 Forwards on Weibo

一、题目大意

  1. PAT A1076
  2. 给出 n 个微博用户的关注情况以及一个转发层数上限 L,并给出最初发布消息的用户编号,求在转发层数上限内消息最多会被多少用户转发。

二、解题思路

  1. 很明显要用 BFS 模拟一层一层的转发过程,结点要存储结点编号以及层数。
  2. 这里使用邻接矩阵来存储有向图,某个结点的邻接表存储的是其粉丝的编号,处理数据时应当注意。参考代码如下。

三、参考代码

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 1010;
struct node {
	int id;
	int layer;
};
vector <node> adj[maxn];
bool inq[maxn];
int BFS(int n, int L) {
	int num_forward = 0;
	node start;
	start.id = n;
	start.layer = 0;
	queue <node> q;
	q.push(start);
	inq[start.id] = true;
	while (q.size()) {
		node temp = q.front();
		q.pop();
		for (int i = 0; i < adj[temp.id].size(); i++) {
			node next = adj[temp.id][i];
			next.layer = temp.layer + 1;
			if (!inq[next.id] && next.layer <= L) {
				q.push(next);
				inq[next.id] = true;
				num_forward++;
			}
		}
	}
	return num_forward;
}

int main() {
	int n, L;
	cin >> n >> L;
	for (int i = 1; i <= n; i++) {
		node temp;
		temp.id = i;
		int num_follower, follower;
		cin >> num_follower;
		for (int i = 0; i < num_follower; i++) {
			cin >> follower;
			adj[follower].push_back(temp);
		}
	}
	int num_query;
	cin >> num_query;
	for (int i = 0; i < num_query; i++) {
		fill(inq, inq + maxn, false);
		int start;
		cin >> start;
		cout << BFS(start, L) << endl;
	}
	return 0;
}

四、解题感悟

  1. 本题属于 BFS 的简单应用啦。

猜你喜欢

转载自blog.csdn.net/weixin_42717165/article/details/87816855
今日推荐