LCA入门题。给一颗树,若干询问,对每个询问输出它们的LCA。离线算法(Tarjan)模板。
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<string>
#include<queue>
#include<map>
///LOOP
#define REP(i, n) for(int i = 0; i < n; i++)
#define FF(i, a, b) for(int i = a; i < b; i++)
#define FFF(i, a, b) for(int i = a; i <= b; i++)
#define FD(i, a, b) for(int i = a - 1; i >= b; i--)
#define FDD(i, a, b) for(int i = a; i >= b; i--)
///INPUT
#define RI(n) scanf("%d", &n)
#define RII(n, m) scanf("%d%d", &n, &m)
#define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k)
#define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p)
#define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q)
#define RFI(n) scanf("%lf", &n)
#define RFII(n, m) scanf("%lf%lf", &n, &m)
#define RFIII(n, m, k) scanf("%lf%lf%lf", &n, &m, &k)
#define RFIV(n, m, k, p) scanf("%lf%lf%lf%lf", &n, &m, &k, &p)
#define RS(s) scanf("%s", s)
///OUTPUT
#define PN printf("\n")
#define PI(n) printf("%d\n", n)
#define PIS(n) printf("%d ", n)
#define PS(s) printf("%s\n", s)
#define PSS(s) printf("%s ", s)
#define PC(n) printf("Case %d: ", n)
///OTHER
#define PB(x) push_back(x)
#define CLR(a, b) memset(a, b, sizeof(a))
#define CPY(a, b) memcpy(a, b, sizeof(b))
#define display(A, n, m) {REP(i, n){REP(j, m)PIS(A[i][j]);PN;}}
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int MOD = 1e9+7;
const int INFI = 1e9 * 2;
const LL LINFI = 1e17;
const double eps = 1e-6;
const int N = 1111;
const int M = N << 2;
const int move[8][2] = {0, 1, 0, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1};
vector<int> v[N], q[N];
int f[N], cnt[N], n, m;
bool vis[N];
int find(int x){return x == f[x] ? x : f[x] = find(f[x]);}
void lca(int x)
{
int k = v[x].size(), u;
f[x] = x;
REP(i, k)lca(u = v[x][i]), f[u] = x;
vis[x] = 1;
k = q[x].size();
REP(i, k)if(vis[u = q[x][i]])cnt[find(u)]++;
}
inline void get(int &a)
{
char c;
while(((c = getchar()) < '0' || c > '9'));
for(a = 0; c >= '0' && c <= '9';a = a * 10 + c - '0', c = getchar());
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int a, k, b;
while(RI(n) != EOF)
{
CLR(vis, 0);
CLR(f, 0);
REP(i, n + 1)v[i].clear(), q[i].clear();
REP(i, n)
{
get(a),get(k);
while(k--)
{
RI(b);
f[b] = a;
v[a].PB(b);
}
}
RI(m);
while(m--)
{
get(a);
get(b);
q[a].PB(b);
q[b].PB(a);
}
CLR(cnt, 0);
FFF(i, 1, n + 1)if(!f[i])
{
lca(i);
break;
}
REP(i, n + 1)if(cnt[i])printf("%d:%d\n", i, cnt[i]);
}
return 0;
}