题解 洛谷 Luogu P2853 [USACO06DEC] Cow Picnic S 搜索 C++

题目

传送门

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值