//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include<bits/stdc++.h>
#define ll long long
#define F first
#define S second
#define pb push_back
#define pf push_front
#define ppb pop_back
#define ppf pop_front
#define all(x) x.begin(), x.end()
const int mod = 1e9 + 7;
const int N = 100001;
using namespace std;
ll n, q, m, a, b, c, d[N], cntleaves, p[N], used[N], cnt[N], ans, us[3];
vector <ll> g[N], dr, gl[N];
deque <pair <ll, ll>> sol;
deque <ll> st;
void dfs (ll v, ll pr){
for (auto i: g[v]){
if (i != pr){
d[i] = d[v] + 1;
dfs (i, v);
}
}
}
void ch (ll v, ll pr){
for (auto i: g[v]){
if (i != pr){
ch (i, v);
d[v] = max (d[v], d[i]);
}
}
}
void LT (ll v, ll pr, ll dep){
if (g[v].size() == 1){
st.pb (dep);
}
for (auto i: g[v]){
if (i != pr){
LT (i, v, dep + 1);
}
}
}
signed main (){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> q;
for (int i = 1; i < n; i++){
cin >> a >> b;
g[a].pb (b);
g[b].pb (a);
}
for (int i = 1; i <= n; i++){
if (g[i].size() == 1){
cntleaves++;
}
}
d[1] = 1;
dfs (1, 1);
a = b = 0;
for (int i = 1; i <= n; i++){
if (a < d[i]){
a = d[i];
b = i;
}
}
d[b] = 1;
dfs (b, b);
ch (b, b);
st.pb (b);
used[b] = 1;
while (st.size()){
a = st[0];
dr.pb (a);
st.ppf();
for (auto i: g[a]){
if (used[i] == 0 && d[i] == d[a]){
st.pb (i);
used[i] = 1;
break;
}
}
}
for (auto i: dr){
for (auto j: g[i]){
st.clear();
if (used[j] == 0){
LT (j, i, 1);
for (auto y: st){
gl[i].pb (y);
}
}
}
}
// for (int i = 1; i <= n; i++){
// cout << used[i];
// }
// cout << '\n';
for (int z = 1; z <= q; z++){
cin >> m;
a = 0;
b = 0;
us[0] = us[1] = 0;
for (int j = 1; j <= m; j++){
cin >> p[j];
if (used[p[j]] == 1){
if (p[j] == dr[0] && us[0] == 0){
b++;
us[0] = 1;
}
else if (dr.size() > 1 && p[j] == dr.back() && us[1] == 0){
b++;
us[1] = 1;
}
else{
a++;
gl[p[j]].pb (1);
cnt[p[j]]++;
}
}
else{
b++;
}
}
if ((cntleaves + a) % 2){
for (int i = 0; i < dr.size(); i++){
while (cnt[i] > 0){
cnt[i]--;
gl[i].ppb();
}
}
cout << "-1\n";
continue;
}
ans = 0;
ans += dr.size() - 1;
sol.clear();
for (int i = 0; i < dr.size(); i++){
for (auto j: gl[dr[i]]){
if (sol.size()){
ans += sol[0].F + j + (i - sol[0].S);
sol.ppf();
}
else{
sol.pb ({j, i});
}
}
}
for (int i = 0; i < dr.size(); i++){
while (cnt[i] > 0){
cnt[i]--;
gl[i].ppb();
}
}
cout << ans + b << '\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |