This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<iostream>
#include<stack>
#include<map>
#include<vector>
#include<string>
#include<unordered_map>
#include <queue>
#include<cstring>
#include <cassert>
#include<limits.h>
#include<cmath>
#include<set>
#include<algorithm>
#include<bitset>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define ll long long
#define f first
#define endl "\n"
#define s second
#define pii pair<int,int>
#define ppii pair<int,pii>
#define vi vector<int>
#define pb push_back
//#define p push
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define F(n) for(int i=0;i<n;i++)
#define lb lower_bound
#define ub upper_bound
#define fastio ios::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
#pragma GCC optimize ("03,unroll-loops")
#define int long long
const int mxn=1e5+5,inf=1e9,lg=30,mod=1e9+7;
int n,q;
vector<int>adj[mxn+10];
int val[mxn+10],ans=0,up[mxn+10],cnt=0;
bool leaf[mxn+10],yes[mxn+10];
int st=1;
void dfs(int cur,int p){
for(auto i:adj[cur]){
if(i==p)continue;
dfs(i,cur);
up[i]=cur;
val[cur]+=val[i];
}
if(val[cur]==0||val[cur]%2)val[cur]=1;
else val[cur]=2;
if(cur!=st)ans+=val[cur];
}
int32_t main(){
fastio
cin>>n>>q;
for(int i=0;i<n-1;i++){
int a,b;cin>>a>>b;
adj[a].pb(b);
adj[b].pb(a);
}
for(int i=1;i<=n;i++)if(adj[i].size()==2)st=i;
for(int i=1;i<=n;i++){
if(adj[i].size()==1){
leaf[i]=true;
if(i!=st)val[i]++;
cnt++;
}
}
dfs(st,-1);
while(q--){// brute force,check idea
int m;cin>>m;
vector<int>v(m);
for(int i=0;i<m;i++){
cin>>v[i];
int a=v[i];
if(!leaf[a]||yes[a]){
cnt++;
while(a!=st){
if(val[a]==1)val[a]=2,ans++;
else val[a]=1,ans--;
a=up[a];
}
}
else yes[a]=true;
}
for(auto i:v)yes[i]=false;
cout<<((cnt%2)?-1:ans+m)<<'\n';
for(auto i:v){
int a=i;
if(!leaf[a]||yes[a]){
cnt--;
while(a!=st){
if(val[a]==1)val[a]=2,ans++;
else val[a]=1,ans--;
a=up[a];
}
}
else yes[a]=true;
}
for(auto i:v)yes[i]=false;
}
return 0;
}
# | 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... |