1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
| #include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> hhhh;
int tot = 1;
typedef long long ll;
const int maxn = 200005;
int T, n, m;
struct edge_type {
int to, next;
} edge[maxn << 1];
int cnte = 0, h[maxn];
void ins(int u, int v) {
edge[++cnte].to = v;
edge[cnte].next = h[u];
h[u] = cnte;
}
int siz[maxn], son[maxn], top[maxn], fa[maxn], dis[maxn], du[maxn];
void dfs1(int now, int father, int deep) {
fa[now] = father;
dis[now] = deep;
siz[now] = 1;
int t = 0;
for (int i = h[now]; i; i = edge[i].next) {
if (edge[i].to == father) continue;
dfs1(edge[i].to, now, deep+1);
siz[now] += siz[edge[i].to];
if (siz[edge[i].to] > siz[t]) t = edge[i].to;
}
son[now] = t;
}
void dfs2(int now, int father, int tp) {
top[now] = tp;
if (son[now]) {
dfs2(son[now], now, tp);
for (int i = h[now]; i; i = edge[i].next) {
if (edge[i].to == father || edge[i].to == son[now]) continue;
dfs2(edge[i].to, now, edge[i].to);
}
}
}
int lca(int u, int v) {
while (top[u] != top[v]) {
if (dis[top[u]] < dis[top[v]]) swap(u, v);
u = fa[top[u]];
}
if (dis[u] > dis[v]) return v;
return u;
}
char str[50];
int main() {
cin.tie(0);
cin.sync_with_stdio(false);
cout.tie(0);
cout.sync_with_stdio(false);
cin >> T;
while (T--) {
hhhh.clear();
tot = 1;
cin >> n >> m;
for (int i = 0; i <= n; ++i) h[i] = du[i] = 0;
int x, y;
for (int i = 1; i < n; ++i) {
cin >> str;
if (hhhh.find(str) == hhhh.end()) hhhh[str] = tot++;
x = hhhh[str];
cin >> str;
if (hhhh.find(str) == hhhh.end()) hhhh[str] = tot++;
y = hhhh[str];
ins(x, y);
ins(y, x);
++du[x];
}
int rt;
for (int i = 1; i < tot; ++i) if (du[i] == 0) { rt = i; break; }
dfs1(rt, -1, 1);
dfs2(rt, -1, rt);
for (int i = 0; i < m; ++i) {
cin >> str;
x = hhhh[str];
cin >> str;
y = hhhh[str];
int l = lca(x, y);
int ans = dis[x] - dis[l];
if (l != y) ++ans;
cout << ans << endl;
}
}
return 0;
}
|