POJ 3660 Cow Contest
对每个结点 BFS 一遍,找出能被它打败和可以打败它的结点的总和 s ,如果 s == n-1 ,它的排名可以确定;
C++ vector 邻接表;
# include <cstdio> # include <iostream> # include <cstring> # include <vector> # define N 105 using namespace std; int n, m; char vis[N]; vector <int> pre[N]; vector <int> aft[N]; int bfs(int u, int d) { int i, ret, cx, nx, front, rear, size; int Q[1000*N]; Q[1] = u; memset(vis, 0, sizeof(vis)); vis[u] = 1; front = 1; rear = 2; ret = 0; while (front < rear) { cx = Q[front++]; size = d>0 ? aft[cx].size():pre[cx].size(); for (i = 0; i < size; ++i) { nx = d>0 ? aft[cx][i]:pre[cx][i]; if (!vis[nx]) { Q[rear++] = nx; vis[nx] = 1; ++ret; } } } return ret; } int main() { int i, cnt, u, v; while (~scanf("%d%d", &n, &m)) { for (i = 1; i <= n; ++i) { pre[i].clear(); aft[i].clear(); } for (i = 0; i < m; ++i) { scanf("%d%d", &u, &v); pre[v].push_back(u); aft[u].push_back(v); } cnt = 0; for (i = 1; i <= n; ++i) { if (bfs(i, 1)+bfs(i, -1) == n-1) ++cnt; } printf("%d\n", cnt); } return 0; }
//