Bzoj 1648(DFS)

BZOJ 1648
Luogu 2853
from: USACO 2006 Dec Sliver(USACO刷题第8题)

记录一下每个牧场的奶牛个数,之后如果一个牧场有牛就dfs遍历,把遍历到的点的$tot[i]$都加上这个奶牛数,然后最后统计每个牧场如果$tot[i]=k$那么就是一个答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#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;
}

------ 本文结束 ------