Cow picnic
| Time limit:2000 ms |
|
Memory limit:65536 K |
| Total submissions:4607 |
|
Accepted:1848 |
Description
The cows are having a picnic! Each of Farmer John'sK(1 ≤K≤ 100) cows is grazing in oneN(1 ≤N≤ 1,000) pastures, conveniently numbered 1...N. The pastures are connectedM(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 4231 21 42 33 4
Sample output
2
Hint
The cows can meet in pastures 3 or 4.
Source
Usaco 2006 December silver
#include<iostream>using namespace std;const int N=1001;int sum[N];int start[N];int path[N][N];bool vis[N];int k,m,n;void dfs(int s){ int i; sum[s]++; vis[s]=true; for(i=1;i<=n;i++) { if(path[s][i]==1&&vis[i]==false) dfs(i); }}int main(){ //freopen("test.txt","r",stdin); int i,j; int p1,p2; scanf("%d%d%d",&k,&n,&m); for(i=1;i<=k;i++) scanf("%d",&start[i]); memset(path,0,sizeof(path)); memset(sum,0,sizeof(sum)); for(i=1;i<=m;i++) { scanf("%d%d",&p1,&p2); path[p1][p2]=1; } for(i=1;i<=k;i++) { memset(vis,false,sizeof(vis)); dfs(start[i]); } int ans=0; for(i=1;i<=n;i++) if(sum[i]==k) ans++; printf("%d\n",ans); return 0;}