题目
传送门
P2853 [USACO06DEC] Cow Picnic S - 洛谷 | 计算机科学教育新生态https://www.luogu.com.cn/problem/P2853
思路
分别以每头奶牛所在的牧场为起点进行搜索,每轮搜索不重复搜
用计数变量统计每个牧场被搜到到的次数,次数 = 奶牛总数,就计入答案
代码
#include <vector>
#include <iostream>
using namespace std;
const int K = 105, N = 1005;
vector<int> g[N];
int k, n, m, cow[K], q[N], cnt[N], ans;
void BFS(int a)
{
int head = 0, tail = -1;
bool mk[N]{};
q[++tail] = a;
mk[a] = true;
while (head <= tail)
{
int x = q[head++];
cnt[x]++;
for (auto X : g[x])
if (mk[X] == false)
q[++tail] = X, mk[X] = true;
}
}
int main()
{
scanf("%d%d%d", &k, &n, &m);
for (int i = 0; i < k; i++)
scanf("%d", &cow[i]);
for (int i = 0; i < m; i++) //建图
{
int x, y;
scanf("%d%d", &x, &y);
g[x].push_back(y);
}
for (int i = 0; i < k; i++) //分别搜索,计数
BFS(cow[i]);
for (int i = 1; i <= n; i++) //统计答案
if (cnt[i] == k)
ans++;
printf("%d", ans);
return 0;
}