Cow Picnic
Time Limit:2000MS Memory Limit:65536K Total Submissions:5811 Accepted:2388 Description
The cows are having a picnic! Each of Farmer John'sK(1 ≤K≤ 100) cows is grazing in one ofN(1 ≤N≤ 1,000) pastures, conveniently numbered 1...N. The pastures are connected byM(1 ≤M≤ 10,000) one-way paths (no path connects a pasture to itself).
The cows want to gather in the same pasture for their picnic, but (because of the one-way paths) some cows may only be able to get to some pastures. Help the cows out by figuring out how many pastures are reachable by all cows, and hence are possible picnic locations.
Input
Line 1: Three space-separated integers, respectively: K, N, and M
Lines 2.. K+1: Line i+1 contains a single integer (1.. N) which is the number of the pasture in which cow iis grazing.
Lines K+2.. M+ K+1: Each line contains two space-separated integers, respectively Aand B(both 1.. Nand A!= B), representing a one-way path from pasture Ato pasture B.Output
Line 1: The single integer that is the number of pastures that are reachable by all cows via the one-way paths.Sample Input
2 4 4 2 3 1 2 1 4 2 3 3 4Sample Output
2Hint
The cows can meet in pastures 3 or 4.Source
从每头牛开始的地方dfs一下。。。经过的点x全部cnt[x]++。。。然后看一下那些点的cnt值等于k。。。
用到了一个小trick。。。vis[i][j]表示点i是否第j头牛曾经经过。。。
(空间换时间。。。)
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <string>
#include <cfloat>
#include <stack>
#include <cassert>
using namespace std;
int k, n, m, val[1010], cow[110], head[10010], rest[10010], to[10010], tot, vis[10010][110], ans;
void add(int u, int v) {
tot ++;
to[tot] = v;
rest[tot] = head[u];
head[u] = tot;
}
void dfs(int u, int ext) {
vis[u][ext] = 1;
val[u] ++;
for(int i = head[u] ; i ; i = rest[i]) {
int v = to[i];
if(vis[v][ext]) continue;
dfs(to[i], ext);
}
}
int main() {
scanf("%d%d%d", &k, &n, &m);
for(int i = 1 ; i <= k ; i ++) {
scanf("%d", &cow[i]);
}
for(int i = 1, a, b ; i <= m ; i ++) {
scanf("%d%d", &a, &b);
add(a, b);
}
for(int i = 1 ; i <= k ; i ++) {
dfs(cow[k], i);
}
for(int i = 1 ; i <= n ; i ++) {
if(val[i] == k) {
ans ++;
}
}
printf("%d\n", ans);
}