poj3256
bfs
View Code
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; #define maxc 105 #define maxn 1005 #define maxm 10005 struct Edge { int v, next; } edge[maxm]; int cow, n, m; int head[maxn]; int ncount; bool vis[maxn]; int reach[maxn]; int q[maxn]; int pos[maxc]; void addedge(int a, int b) { edge[ncount].v = b; edge[ncount].next = head[a]; head[a] = ncount++; } void input() { scanf("%d%d%d", &cow, &n, &m); for (int i = 0; i < cow; i++) { scanf("%d", &pos[i]); pos[i]--; } for (int i = 0; i < m; i++) { int a, b; scanf("%d%d", &a, &b); addedge(a - 1, b - 1); } } void bfs(int s) { int front = 0, rear = 0; q[rear++] = s; vis[s] = true; while (front != rear) { int u = q[front++]; reach[u]++; for (int i = head[u]; ~i; i = edge[i].next) { int v = edge[i].v; if (vis[v]) continue; q[rear++] = v; vis[v] = true; } } } int work() { memset(reach, 0, sizeof(reach)); for (int i = 0; i < cow; i++) { memset(vis, 0, sizeof(vis)); bfs(pos[i]); } int ret = 0; for (int i = 0; i < n; i++) if (reach[i] == cow) ret++; return ret; } int main() { //freopen("t.txt", "r", stdin); memset(head, -1, sizeof(head)); ncount = 0; input(); printf("%d\n", work()); return 0; }