제출 #1159367

#제출 시각아이디문제언어결과실행 시간메모리
1159367Kaztaev_AlisherSpring cleaning (CEOI20_cleaning)C++20
9 / 100
1096 ms21948 KiB
#include <bits/stdc++.h> #define ios ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout) #define all(a) a.begin() , a.end() #define F first #define S second using namespace std; using ll = long long; const ll N = 2e5+5 , inf = 2e9 + 7; const ll INF = 1e18 , mod = 1e9+7; ll a[N] , b[N] , mx , par[N] , was[N] , dp[N] , sz[N]; vector<int> g[N]; void dfs(int v, int p){ dp[v] = dp[p]+1; par[v] = p; if(dp[v] > dp[mx]) mx = v; for(int to : g[v]){ if(to != p){ dfs(to,v); } } } int cur = 0; void go(int v , int p){ int ans = 0; dp[v] = dp[p]+1; sz[v] = 0; for(int to : g[v]){ if(to != p && was[to] == 0){ go(to,v); sz[v] += sz[to]; } } if(g[v].size() == 1) sz[v] = 1; else if(sz[v] == 2){ ans++; } else if(sz[v] == 1){ ans = 0; } else { sz[v] %= 3; ans += sz[v]-1; } cur += ans; } void solve(){ int n , q; cin >> n >> q; for(int i = 1; i < n; i++){ cin >> a[i] >> b[i]; } while(q--){ int k; cin >> k; for(int i = 1; i <= n+k; i++) g[i].clear() , was[i] = par[i] = 0; for(int i = 1; i < n; i++){ g[a[i]].push_back(b[i]); g[b[i]].push_back(a[i]); } for(int i = 1; i <= k; i++){ int a; cin >> a; g[a].push_back(i+n); g[i+n].push_back(a); } ll res = 0 , ind = 0; for(int i = 1; i <= n+k; i++) res += (g[i].size() == 1); if(res % 2){ cout << "-1\n"; continue; } mx = 1; dfs(1,0); dfs(mx,0); vector<int> path; while(mx > 0){ path.push_back(mx); mx = par[mx]; } reverse(all(path)); cur = 0; vector<ll> bar; for(int x : path) was[x] = 1; for(int x : path){ ind++; for(int to : g[x]){ if(was[to] == 0){ dp[x] = 0; go(to,x); ll ans = 0; while(sz[to] > 0){ if(bar.size()){ ans += ind-bar.back(); bar.pop_back(); } else { bar.push_back(ind); } sz[to]--; } cur += ans; } } } if(res % 2) cout << "-1\n"; else cout << cur+n+k-1 << "\n"; } } /* */ signed main(){ ios; solve(); }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...