思路:DFS全图,记录每个牧场可以到达的牛的数量,若pa[v] == K,则所有牛可以到达。
#include#include #include #define MAX 10005using namespace std;typedef struct{ int to, next;}Node;Node edge[MAX];int head[1005], vis[1005], pa[MAX], in[MAX];void dfs(int s){ for(int i = head[s];i != -1;i = edge[i].next){ int v = edge[i].to; if(!vis[v]){ pa[v] ++; vis[v] = 1; dfs(v); } }}int main(){ int K, N, M, u, v; /* freopen("in.c", "r", stdin); */ while(~scanf("%d%d%d", &K, &N, &M)){ memset(head, -1, sizeof(head)); memset(pa, 0, sizeof(pa)); for(int i = 1;i <= K;i ++){ scanf("%d", &in[i]); pa[in[i]] ++; } for(int i = 1;i <= M;i ++){ scanf("%d%d", &u, &v); edge[i].to = v; edge[i].next = head[u]; head[u] = i; } for(int i = 1;i <= K;i ++){ memset(vis, 0, sizeof(vis)); vis[in[i]] = 1; dfs(in[i]); } int ans = 0; for(int i = 1;i <= N;i ++) if(pa[i] == K) ans ++; cout << ans << endl; } return 0;}