..
# Include <iostream> # include <cstdio> # include <cstring> # include <map> # include <vector> using namespace std; const int maxn = 1111; int head [maxn]; int len; struct Node {int to; int next;} e [maxn * 2]; int father [maxn]; int color [maxn]; int vis [maxn]; int gg [maxn]; vector <int> q [maxn]; void add (int from, int to) {e [len]. to = to; e [len]. next = head [from]; head [from] = len ++;} int getfather (int x) {if (father [x]! = X) father [x] = getfather (father [x]); return father [x];} void un (int a, int B) {int fa = getfather (a); int fb = getfather (B); father [fb] = fa;} void dfs (int x) {for (int I = head [x]; ~ I; I = e [I]. next) {int cc = e [I]. to; dfs (cc); un (x, cc);} color [x] = 1; for (int I = 0; I <q [x]. size (); I ++) {int t = q [x] [I]; if (color [t]) {int t1 = getfather (q [x] [I]); vis [t1] ++ ;}}} void init (int n) {len = 0; memset (head, -1, sizeof (head); for (int I = 1; I <= n; I ++) father [I] = I; memset (head,-1, sizeof (head); for (int I = 1; I <= n; I ++) q [I]. clear (); memset (color, 0, sizeof (color); (Int I = 1; I <= n; I ++) vis [I] = 0; for (int I = 1; I <= n; I ++) gg [I] = 0;} int main () {int n; while (cin> n) {init (n); int m, a, B, c; for (int I = 0; I <n; I ++) {scanf ("% d", & a); scanf (":( % d)", & B ); for (int j = 0; j <B; j ++) {scanf ("% d", & c); add (a, c ); gg [c] = 1 ;}}scanf ("% d", & m); while (m --) {scanf ("(% d)", &, & B); // printf ("% d % djiji \ n", a, B); q [a]. push_back (B); q [B]. push_back ();} Int root; for (int I = 1; I <= n; I ++) if (! Gg [I]) {root = I; break;} dfs (root); for (int I = 1; I <= n; I ++) {if (vis [I]) {printf ("% d: % d \ n", I, vis [I]) ;}} return 0 ;}
Poj1470 Closest Common Ancestors LCA