PAT (Advanced) 1076. Forwards on Weibo (30)

#include <iostream>
#include <cstring>

using namespace std;

const int MAX = 1000;
bool edge[MAX][MAX];
bool visited[MAX];
int queue[MAX];

int BFS(int start, int n, int level)
{
	int res = 0;
	int front = 0, rear = 1, level_last;
	queue[front] = start;
	visited[start] = true;
	while (front < rear)
	{
		level_last = rear;
		level--;
		while (front < level_last)
		{
			int i = queue[front++];
			for (int j = 0; j < n; j++)
			{
				if (!visited[j] && edge[i][j])
				{
					visited[j] = true;
					res++;
					queue[rear++] = j;
				}
			}
		}
		if (level == 0)
			break;
	}
	return res;
}

int main()
{
	int N, L;
	cin >> N >> L;
	int M, s;
	for (int i = 0; i < N; i++)
	{
		cin >> M;
		for (int j = 0; j < M; j++)
		{
			cin >> s;
			edge[s - 1][i] = true;
		}
	}
	int K;
	int start;
	int sum;
	cin >> K;
	for (int i = 0; i < K; i++)
	{
		memset(visited, false, sizeof(visited));
		cin >> start;
		cout << BFS(start - 1, N, L) << endl;
	}
}

你可能感兴趣的:(PAT (Advanced) 1076. Forwards on Weibo (30))