Submission #578193

#TimeUsernameProblemLanguageResultExecution timeMemory
578193tengiz05Spring cleaning (CEOI20_cleaning)C++17
35 / 100
110 ms19468 KiB
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct SegmentTree { int n; vector<int> t; SegmentTree(int n) : n(n), t(2 * n) {} int get(int l, int r) { int res = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l & 1) res ^= t[l++]; if (r & 1) res ^= t[--r]; } return res; } void update(int x) { for (x += n; x > 0; x >>= 1) { t[x] ^= 1; } } }; /* 7 3 1 2 2 4 4 5 5 6 5 7 3 4 1 4 2 2 4 5 6 6 5 4 2 */ int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, q; cin >> n >> q; vector<vector<int>> e(n); vector<int> deg(n); for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; u--; v--; e[u].push_back(v); e[v].push_back(u); deg[u]++; deg[v]++; } vector<int> c(n), in(n), out(n); vector s(2, vector<int>(n)); int timeStamp = 0; int cnt = 0; function<void(int, int)> dfs = [&](int u, int p) { in[u] = timeStamp++; c[u] = deg[u] <= 1; cnt += c[u]; for (int v : e[u]) { if (v != p) { dfs(v, u); c[u] ^= c[v]; } } out[u] = timeStamp; }; dfs(0, -1); int f[2] {}; dfs = [&](int u, int p) { if (p != -1) { s[1][u] += c[u]; s[0][u] += !c[u]; f[c[u]]++; } for (int v : e[u]) { if (v != p) { s[1][v] = s[1][u]; s[0][v] = s[0][u]; dfs(v, u); } } }; dfs(0, -1); SegmentTree t(n); while (q--) { int k; cin >> k; vector<int> d(k); for (int i = 0; i < k; i++) { cin >> d[i]; d[i]--; } set<int> v(d.begin(), d.end()); int leaves = cnt + k; for (int x : v) { if (deg[x] <= 1) { leaves--; } } if (leaves % 2 != 0) { cout << "-1\n"; continue; } int a[2] {f[0], f[1]}; sort(d.begin(), d.end(), [&](int i, int j) { return in[i] > in[j]; }); for (int u : d) { if (deg[u] > 1) { int x = t.get(in[u], out[u]); a[1] -= s[1 ^ x][u]; a[1] += s[0 ^ x][u]; a[0] -= s[0 ^ x][u]; a[0] += s[1 ^ x][u]; t.update(in[u]); } deg[u]++; } int ans = 2 * a[0] + a[1] + k; cout << ans << "\n"; reverse(d.begin(), d.end()); for (int u : d) { deg[u]--; if (deg[u] > 1) { t.update(in[u]); } } } return 0; }
#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...