A1076 Forwards on Weibo [图的遍历bfs]

A1076 Forwards on Weibo [图的遍历bfs]_第1张图片
题目大意:给出查询,求微博的可能的最大转发数量。给出k个人和他关注的人,然后给查询人。用邻接表实现

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxv = 1001;
struct node
{
	int id;
	int layer;
};

vector<node>adj[maxv];
bool inq[maxv];

int bfs(int s, int l)
{
	int numFoward = 0;
	queue<node>q;
	node start;
	start.id = s;
	start.layer = 0;
	q.push(start);
	inq[start.id] = true;
	while (!q.empty())
	{
		node topnode = q.front();
		q.pop();
		int u = topnode.id;
		for (int i = 0; i < adj[u].size(); i++)
		{
			node next = adj[u][i];
			next.layer = topnode.layer + 1;
			if (inq[next.id] == false && next.layer <= l)
			{
				q.push(next);
				inq[next.id] = true;
				numFoward++;
			}
		}
	}
	return numFoward;
}

int main()
{
	int n, m, l, king;
	cin >> n >> l;
	node user;
	for (int i = 1; i <= n; i++)
	{
		//node* Node = new node;
		//Node->id = i;
		user.id = i;
		cin >> m;
		for (int j = 0; j < m; j++)
		{
			cin >> king;
			adj[king].push_back(user);
		}
	}
	int numquery, s;
	cin >> numquery;
	for (int i = 0; i < numquery; i++)
	{
		memset(inq, false, sizeof(inq));
		cin >> s;
		int numFoward = bfs(s, l);
		cout << numFoward << endl;
	}
}

你可能感兴趣的:(BFS,图的应用,PAT-甲级(持续更新))