#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define pb push_back
#define ff first
#define ss second
struct ST{
vector<int> t;
vector<bool> p;
int n;
ST(int ns){
n = ns;
t.resize(4 * n);
p.resize(4 * n);
}
void push(int v, int tl, int tr){
if (!p[v]) return;
int vv = 2 * v, tm = (tl + tr) / 2;
t[vv] = (tm - tl + 1) - t[vv];
t[vv + 1] = (tr - tm) - t[vv + 1];
p[vv] = !p[vv]; p[vv + 1] = !p[vv + 1];
p[v] = 0;
}
void upd(int v, int tl, int tr, int l, int r){
if (l > tr || r < tl) return;
if (l <= tl && tr <= r){
p[v] = !p[v];
t[v] = (tr - tl + 1) - t[v];
return;
}
int tm = (tl + tr) / 2, vv = 2 * v;
push(v, tl, tr);
upd(vv, tl, tm, l, r);
upd(vv + 1, tm + 1, tr, l, r);
t[v] = t[vv] + t[vv + 1];
}
void upd(int l, int r){
upd(1, 1, n, l, r);
}
int get(){
return t[1];
}
};
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, q; cin>>n>>q;
vector<int> g[n + 1];
for (int i = 1; i < n; i++){
int u, v; cin>>u>>v;
g[u].pb(v);
g[v].pb(u);
}
vector<int> sz(n + 1), h(n + 1), p(n + 1);
function<void(int, int)> fill = [&](int v, int pr){
sz[v] = 1; p[v] = pr;
for (int i: g[v]){
if (i == pr) continue;
fill(i, v);
sz[v] += sz[i];
if (sz[i] > sz[h[v]]){
h[v] = i;
}
}
};
fill(1, 0);
vector<int> pos(n + 1), head(n + 1);
int timer = 0;
function<void(int, int)> fill_hld = [&](int v, int k){
pos[v] = ++timer; head[v] = k;
if (!h[v]) return;
fill_hld(h[v], k);
for (int i: g[v]){
if (!pos[i]){
fill_hld(i, i);
}
}
};
fill_hld(1, 1);
vector<int> f(n + 1);
ST T(n);
auto upd = [&](int v){
f[1] = !f[1];
while (v > 0){
T.upd(pos[head[v]], pos[v]);
v = p[head[v]];
}
};
int lf = 0;
for (int i = 1; i <= n; i++){
if (g[i].size() == 1){
upd(i);
lf++;
}
}
vector<bool> used(n + 1);
vector<int> v;
while (q--){
int d; cin>>d;
vector<int> a(d + 1);
int cc = lf + d;
for (int i = 1; i <= d; i++){
cin>>a[i];
if (g[a[i]].size() > 1) continue;
if (!used[a[i]]){
cc--;
used[a[i]] = 1;
}
}
if (cc % 2){
cout<<-1<<"\n";
for (int i = 1; i <= d; i++){
used[a[i]] = 0;
}
continue;
}
v.clear();
int out = d;
for (int i = 1; i <= d; i++){
if (used[a[i]]){
used[a[i]] = 0;
continue;
}
upd(a[i]);
v.pb(a[i]);
}
int k = T.get() - f[1];
out += (k + (n - k - 1) * 2);
cout<<out<<"\n";
for (int i: v){
upd(i);
}
}
}
# | 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... |