The actual query volume is about, which is faster offline.
# Include <cstdio> # include <cstring> # include <algorithm> # include <map> # include <set> # include <bitset> # include <queue> # include <stack> # include <string> # include <iostream> # include <cmath> # include <climits> using namespace std; const int maxn = 1000; struct Edge {int u, v, id; Edge (int u, int v, int id = 0): u (u), v (v ), id (id) {}}; vector <Edge> e [maxn], q [maxn]; int n, fa [maxn], ans [260000], col [maxn], pfa [m Axn]; map <int, int> mp; int getfa (int u) {return fa [u] = u? U: fa [u] = getfa (fa [u]);} void dfs (int now) {int qsize = q [now]. size (); col [now] = 1; for (int I = 0; I <qsize; I ++) if (ans [q [now] [I]. id] =-1) {int v = q [now] [I]. v; if (col [v]! = 0) ans [q [now] [I]. id] = getfa (v);} int esize = e [now]. size (); for (int I = 0; I <esize; I ++) {int v = e [now] [I]. v; dfs (v); fa [v] = now ;}} int main () {while (scanf ("% d", & n )! = EOF) {for (int I = 1; I <= n; I ++) {e [I]. clear (); q [I]. clear (); fa [I] = I; col [I] = 0;} memset (pfa,-1, sizeof (pfa); for (int I = 1; I <= n; I ++) {int now, cnt; scanf ("% d :( % d)", & now, & cnt); for (int j = 0; j <cnt; j ++) {int tmp; scanf ("% d", & tmp); e [now]. push_back (Edge (now, tmp); pfa [tmp] = now ;}} int qcnt; scanf ("% d", & qcnt); char kk; memset (ans, -1, sizeof (ans); for (int I = 1; I <= qcnt; I ++) {int a, B ; Scanf ("% c % d % c", & kk, & a, & B, & kk); q [a]. push_back (Edge (a, B, I); q [B]. push_back (Edge (B, a, I);} int root; for (int I = 1; I <= n; I ++) if (pfa [I] =-1) root = I; dfs (root); mp. clear (); for (int I = 1; I <= qcnt; I ++) mp [ans [I] ++; for (map <int, int> :: iterator I = mp. begin (); I! = Mp. end (); I ++) {cout <I-> first <":" <I-> second <endl ;}} return 0 ;}
POJ 1470 Closest Common Ancestors offline LCA