BZOJ 1648
Luogu 2853
from: USACO 2006 Dec Sliver(USACO刷题第8题)
记录一下每个牧场的奶牛个数,之后如果一个牧场有牛就dfs遍历,把遍历到的点的$tot[i]$都加上这个奶牛数,然后最后统计每个牧场如果$tot[i]=k$那么就是一个答案。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
using namespace std;
const int MAXN = 1000 + 5;
vector<int> G[MAXN];
int cs[MAXN], vi[MAXN], tot[MAXN], k, n, m;
void dfs(int u, int s) {
tot[u] += s;
for (int i=0;i<G[u].size();i++) {
int v = G[u][i];
if (!vi[v]) {
vi[v] = true;
dfs(v, s);
}
}
}
void clear() {
ms(tot, 0);
ms(cs, 0);
}
void init() {
clear();
for (int i=1;i<=k;i++) {
int ki;
scanf("%d", &ki);
cs[ki]++;
}
for (int i=1;i<=m;i++) {
int a, b;
scanf("%d%d", &a, &b);
G[a].push_back(b);
}
}
void solve() {
for (int i=1;i<=n;i++) {
if (cs[i]) {
ms(vi, 0), vi[i] = true;
dfs(i, cs[i]);
}
}
int ans = 0;
for (int i=1;i<=n;i++) if (tot[i]==k) ans++;
printf("%d\n", ans);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
#endif
while (scanf("%d%d%d", &k, &n, &m)==3&&k&&n&&m) init(), solve();
return 0;
}