#include <bits/stdc++.h>
using namespace std;
const int N=200005;
int leaves=0;
struct segtree{
struct info{
int cnt0=0,cnt1=0,lz=0;
int rcnt0(){return (lz?cnt1:cnt0);}
int rcnt1(){return (lz?cnt0:cnt1);}
}v[N<<2];
info pull(info a,info b){
return {a.rcnt0()+b.rcnt0(),a.rcnt1()+b.rcnt1(),0};
}
void push(int id){
v[id<<1].lz^=v[id].lz;
v[id<<1|1].lz^=v[id].lz;
}
void build(int id,int l,int r){
if(r-l==1){
v[id].cnt1=1;
return;
}
int m=(l+r)>>1;
build(id<<1,l,m);
build(id<<1|1,m,r);
}
void add(int id,int a,int b,int l,int r){
if(a<=l&&b>=r){
v[id].lz^=1;
return;
}
int m=(l+r)>>1;
push(id);
if(a<m)add(id<<1,a,b,l,m);
if(b>m)add(id<<1|1,a,b,m,r);
v[id]=pull(v[id<<1],v[id<<1|1]);
}
int ask(){
return v[1].rcnt0();
}
}tr;
vector<int> adj[N],big(N,-1),sz(N,0),pa(N),deg(N,0),gp(N,0);
vector<int> path,place(N,0);
void dfs(int k){
if(deg[k]==1)sz[k]=1;
for(int j:adj[k]){
if(j==pa[k])continue;
pa[j]=k;
dfs(j);
sz[k]+=sz[j];
big[k]=(big[k]==-1||sz[big[k]]<sz[j]?j:big[k]);
}
}
void dfs2(int k){
place[k]=path.size();
path.push_back(k);
if(big[k]!=-1){
gp[big[k]]=gp[k];
dfs2(big[k]);
}
for(int j:adj[k]){
if(j!=big[k]&&j!=pa[k]){
gp[j]=j;
dfs2(j);
}
}
}
void add(int p,int x){
if(x==1&°[p]==1){
leaves--;
return;
}
if(x==-1&°[p]==1){
leaves++;
return;
}
for(int i=p;i>0;i=pa[gp[i]]){
tr.add(1,place[gp[i]],place[i]+1,0,N);
sz[i]+=x;
}
}
int32_t main(){
int n,q;cin>>n>>q;
tr.build(1,0,N);
for(int i=1;i<n;i++){
int a,b;cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int rt=1;
for(int i=1;i<=n;i++){
deg[i]=adj[i].size();
if(deg[i]>=2){
rt=i;
}
else{
leaves+=2;
add(i,1);
}
}
gp[rt]=rt;
dfs(rt);
dfs2(rt);
for(int i=0;i<q;i++){
int t;cin>>t;
int ans=n-1+t;
vector<int> a(t);
for(int j=0;j<t;j++){
cin>>a[j];
add(a[j],1);
deg[a[j]]++;
}
ans+=tr.ask()+1;
int leaf=leaves+t;
for(int j=0;j<t;j++){
deg[a[j]]--;
add(a[j],-1);
}
if(leaf&1){
cout<<-1<<endl;
}
else{
cout<<ans<<endl;
}
}
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
10 ms |
14428 KB |
Output is correct |
2 |
Incorrect |
113 ms |
16144 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
70 ms |
15196 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
97 ms |
15876 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
89 ms |
16616 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
226 ms |
18836 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
343 ms |
21412 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
10 ms |
14428 KB |
Output is correct |
2 |
Incorrect |
113 ms |
16144 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |