-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pikachu And Champions - LCA
94 lines (87 loc) · 2.11 KB
/
Pikachu And Champions - LCA
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
92
93
94
#include <bits/stdc++.h>
using namespace std;
const int MAX_SIZE = 500010;
const int MAX_LEVELS =log2(MAX_SIZE) + 1;
int N, Q;
vector<vector<int>> graph;
int depth[MAX_SIZE];
int parents[MAX_SIZE][MAX_LEVELS];
void dfs(int node, int parent) {
parents[node][0] = parent;
for (int i: graph[node]) {
if (i != parent) {
depth[i] = depth[node] + 1;
dfs(i, node);
}
}
}
int lca(int u, int v) {
if (depth[u] < depth[v]) {
swap(u, v);
}
for (int i = MAX_LEVELS - 1; i >= 0; i --) {
if (depth[u] >= depth[v] + (1 << i)) {
u = parents[u][i];
}
}
if (u == v) {
return u;
}
for (int i = MAX_LEVELS - 1; i >= 0; i --) {
if (parents[u][i] != 0 && parents[u][i] != parents[v][i]) {
u = parents[u][i];
v = parents[v][i];
}
}
return parents[u][0];
}
int main(int argc, const char * argv[]) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N;
int m;
cin >> m;
graph.resize(N + 1);
for (int i = 1; i < N; i ++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
dfs(1, 0);
for (int i = 1; i < MAX_LEVELS; i ++) {
for (int j = 1; j <= N; j ++) {
if (parents[j][i - 1] != 0) {
parents[j][i] = parents[parents[j][i - 1]][i - 1];
}
}
}
for(int i=0;i<m;i++)
{
int k;cin >> k;
int mx = -1;
int a[k];
for(int i=0;i<k;i++)
{
cin >> a[i];
}
int m = 0;
int id =0;
for(int i=1;i<k;i++)
{
int p = depth[a[i]]+depth[a[0]] - 2*depth[lca(a[i],a[0])];
if(p>m)
{
m=p;id=i;
}
}
for(int i=0;i<k;i++)
{
int p = depth[a[i]]+depth[a[id]] - 2*depth[lca(a[i],a[id])];
mx = max(mx,p);
}
cout << mx << '\n';
}
return 0;
}