Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- constexpr int N = 2e5 + 5;
- int n, q;
- int x[N], l, k, in[N];
- vector<int> adj[N];
- int par[N][19], ranks[N];
- void Read()
- {
- cin >> n >> q;
- for (int i = 1; i < n; ++i)
- {
- int u, v;
- cin >> u >> v;
- adj[u].emplace_back(v);
- adj[v].emplace_back(u);
- }
- }
- void dfs(int v)
- {
- in[v] = ++l;
- for (int i = 1; i < 19; ++i)
- par[v][i] = par[par[v][i - 1]][i - 1];
- for (auto i : adj[v])
- if (i != par[v][0])
- {
- ranks[i] = ranks[v] + 1;
- par[i][0] = v;
- dfs(i);
- }
- }
- int LCA(int u, int v)
- {
- if (ranks[u] < ranks[v])
- swap(u, v);
- for (int i = 18; ~i; --i)
- if (ranks[par[u][i]] >= ranks[v])
- u = par[u][i];
- if (u == v)
- return u;
- for (int i = 18; ~i; --i)
- if (par[u][i] != par[v][i])
- {
- u = par[u][i];
- v = par[v][i];
- }
- return par[u][0];
- }
- #define d(x, y) (ranks[x] + ranks[y] - 2 * ranks[LCA(x, y)])
- void Solve()
- {
- ranks[1] = 1;
- dfs(1);
- while (q--)
- {
- cin >> k;
- for (int i = 1; i <= k; ++i)
- cin >> x[i];
- sort(x + 1, x + k + 1, [&](const int &x, const int &y)
- { return in[x] < in[y]; });
- int ans(0);
- for (int i = 1; i < k; ++i)
- ans += d(x[i], x[i + 1]);
- ans += d(x[1], x[k]);
- cout << ans / 2 << '\n';
- }
- }
- int32_t main()
- {
- ios::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- Read();
- Solve();
- }
Add Comment
Please, Sign In to add comment