#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
#define int long long
typedef pair<int, int> pii;
typedef long long ll;
const int N = 2e5 + 1, LOG = 20;
vector<int> arr[N];
int used[N], sz[N], dist[LOG][N], levels[N], par[N];
void dfs(int v, int par) {
sz[v] = 1;
for (int u : arr[v])
if (!used[u] && u != par) {
dfs(u, v);
sz[v] += sz[u];
}
}
int clevel, ans[N];
void dfs1(int v, int par) {
for (int u : arr[v]) {
if (!used[u] && u != par) {
dist[clevel][u] = dist[clevel][v] + 1;
dfs1(u, v);
}
}
}
void cd(int v, int cpar) {
dfs(v, -1);
int csz = sz[v] / 2, prev = -1;
bool flag;
do {
flag = false;
for (int u : arr[v])
if (u != prev && !used[u] && sz[u] > csz) {
prev = v;
v = u;
flag = true;
break;
}
} while (flag);
used[v] = 1;
par[v] = cpar;
levels[v] = levels[cpar] + 1;
clevel = levels[v];
dfs1(v, -1);
for (int u : arr[v])
if (!used[u])
cd(u, v);
}
int query(int v) {
int cans = ans[v];
int stv = v;
while (levels[v] != 1) {
v = par[v];
cans = min(cans, ans[v] + dist[levels[v]][stv]);
}
return cans;
}
void change(int v) {
ans[v] = 0;
int stv = v;
while (levels[v] != 1) {
v = par[v];
ans[v] = min(ans[v], dist[levels[v]][stv]);
}
}
void solve() {
int n, f, s, start;
cin >> n >> start;
start--;
for (int i = 0; i < n; i++) {
for (int j = 0; j < LOG; j++)
dist[j][i] = 0;
used[i] = 0;
arr[i].clear();
levels[i] = -1;
ans[i] = 1e8;
}
vector<int> queries(n);
for (int i = 0; i < n - 1; i++) {
cin >> queries[i];
}
for (int i = 0; i < n - 1; i++) {
cin >> f >> s;
f--;
s--;
arr[f].push_back(s);
arr[s].push_back(f);
}
cd(0, -1);
change(start);
int cans = 1e8;
for (int i = 0; i < n - 1; i++) {
cans = min(cans, query(queries[i] - 1));
change(queries[i] - 1);
cout << cans << " ";
}
cout << "\n";
}
signed main() {
//freopen("input.txt", "r", stdin);
//freopen("output1.txt", "w", stdout);
cin.tie(0)->sync_with_stdio(false);
int t;
cin >> t;
while (t--)
solve();
}
1717D - Madoka and The Corruption Scheme | 1296D - Fight with Monsters |
729D - Sea Battle | 788A - Functions again |
1245B - Restricted RPS | 1490D - Permutation Transformation |
1087B - Div Times Mod | 1213B - Bad Prices |
1726B - Mainak and Interesting Sequence | 1726D - Edge Split |
1726C - Jatayu's Balanced Bracket Sequence | 1726A - Mainak and Array |
1613C - Poisoned Dagger | 475B - Strongly Connected City |
652B - z-sort | 124B - Permutations |
1496C - Diamond Miner | 680B - Bear and Finding Criminals |
1036E - Covered Points | 1015D - Walking Between Houses |
155B - Combination | 1531A - Зингер | color |
1678A - Tokitsukaze and All Zero Sequence | 896A - Nephren gives a riddle |
761A - Dasha and Stairs | 1728B - Best Permutation |
1728A - Colored Balls Revisited | 276B - Little Girl and Game |
1181A - Chunga-Changa | 1728C - Digital Logarithm |