【题目链接】
【算法】
离线tarjan求最近公共祖先
【代码】
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXN 910 int i,n,m,u,v,s,root,tot; int head[MAXN],fa[MAXN],f[MAXN],ans[MAXN]; bool visited[MAXN]; vector<int> query[MAXN]; struct Edge { int to,nxt; } e[MAXN]; inline int find(int x) { if (f[x] == x) return x; return f[x] = find(f[x]); } inline void tarjan(int u) { int i,v; visited[u] = true; f[u] = u; for (i = 0; i < query[u].size(); i++) { v = query[u][i]; if (visited[v]) ans[find(v)]++; } for (i = head[u]; i; i = e[i].nxt) { v = e[i].to; tarjan(v); f[v] = u; } } inline void add(int u,int v) { tot++; e[tot] = (Edge){v,head[u]}; head[u] = tot; } int main() { while (scanf("%d",&n) != EOF) { tot = 0; for (i = 1; i <= n; i++) { head[i] = 0; fa[i] = 0; ans[i] = 0; visited[i] = false; query[i].clear(); } for (i = 1; i <= n; i++) { scanf("%d : (%d)",&u,&s); while (s--) { scanf("%d",&v); add(u,v); fa[v] = u; } } for (i = 1; i <= n; i++) { if (!fa[i]) root = i; } scanf("%d",&m); for (i = 1; i <= m; i++) { scanf(" (%d %d)",&u,&v); query[u].push_back(v); query[v].push_back(u); } tarjan(root); for (i = 1; i <= n; i++) { if (ans[i]) printf("%d:%d ",i,ans[i]); } } return 0; }