#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <vector> #include <cstdio> #include <algorithm> #include <cmath> using namespace std; const int maxn = 1e3+10; const int maxq = 5e5+10; bool flag[maxn]; int n; int count_num[maxq]; int answer[maxq]; bool vis[maxn]; struct Node{ int to, next; }edge[maxn*2]; struct Query{ int to, next; int index; }q[maxq*2]; int tot, head[maxn]; int tt, h[maxn]; int fa[maxn]; int ancester[maxn]; int find_fa(int x){ int a = x; while(x!=fa[x]) x = fa[x]; while(a!=fa[x]) { int z = a; a = fa[a]; fa[z] = x; } return x; } void uni(int u, int v){ int fau = find_fa(u); int fav = find_fa(v); if(fau!=fav){ fa[fau] = fav; } } void init(){ tot = 0; memset(head, -1, sizeof(head)); memset(flag, 0, sizeof(flag)); memset(h, -1, sizeof(h)); tt = 0; for(int i=0; i<maxn; i++) fa[i] = i; memset(ancester, 0, sizeof(ancester)); memset(vis, 0, sizeof(vis)); } void add_edge(int u, int v){ edge[tot].to = v; edge[tot].next = head[u]; head[u] = tot++; } void add_query(int u, int v, int index){ q[tt].to = v; q[tt].next = h[u]; q[tt].index = index; h[u] = tt++; q[tt].to = u; q[tt].next = h[v]; q[tt].index = index; h[v] = tt++; } void LCA(int u){ vis[u] = true; ancester[u] = u; for(int i=head[u]; ~i; i=edge[i].next){ int v = edge[i].to; if(vis[v]) continue; LCA(v); for(int i=0; i<=n; i++) find_fa(i); uni(u, v); ancester[find_fa(u)] = u; } for(int i=h[u]; ~i; i = q[i].next){ int v = q[i].to; if(vis[v]){ answer[q[i].index] = ancester[find_fa(v)]; } } } int main() { while(scanf("%d", &n) != EOF){ int u, num, v; init(); for(int i=0; i<n; i++){ scanf("%d:(%d)", &u, &num); for(int j=0; j<num; j++){ scanf("%d", &v); add_edge(u, v); add_edge(v, u); flag[v] = true; } } int q; scanf("%d", &q); for(int i=0; i<q; i++){ char ch; while(ch = getchar()) if(ch == '('){ scanf("%d %d",&u,&v); ch = getchar(); break; } add_query(u, v, i); } int rt=1; for(int i=1; i<=n; i++){ if(!flag[i]){ rt = i; break; } } LCA(rt); memset(count_num, 0, sizeof(count_num)); for(int i=0; i<q; i++){ count_num[answer[i]]++; } for(int i=1; i<=n; i++){ if(count_num[i]>0){ printf("%d:%d\n", i, count_num[i]); } } } return 0; }
|