Submission #658669

#TimeUsernameProblemLanguageResultExecution timeMemory
6586691zaid1The Xana coup (BOI21_xanadu)C++17
100 / 100
78 ms24268 KiB
#include <bits/stdc++.h> using namespace std; #define int long long #define endl '\n'; const int M = 4e5+5, MOD = 1e9+7; int dp[M][2][2], x[M]; vector<int> node[M]; void dfs(int s, int p = 1) { for (int i:node[s]) { if (i != p) dfs(i, s); } int cnt = 0, a = 0; for (int i:node[s]) { if (i != p) { cnt += dp[i][0][1] < dp[i][0][0]; a += min(dp[i][0][0], dp[i][0][1]); } } dp[s][0][0] = dp[s][1][0] = INT_MAX; for (int i:node[s]) { if (i != p) { if (x[s] != cnt%2) { dp[s][0][0] = min(dp[s][0][0], a+abs(dp[i][0][0]-dp[i][0][1])); dp[s][1][0] = a; } else { dp[s][1][0] = min(dp[s][1][0], a+abs(dp[i][0][0]-dp[i][0][1])); dp[s][0][0] = a; } } } cnt = 0, a = 0; for (int i:node[s]) { if (i != p) { cnt += dp[i][1][0] > dp[i][1][1]; a += min(dp[i][1][0], dp[i][1][1]); } } dp[s][0][1] = dp[s][1][1] = INT_MAX; for (int i:node[s]) { if (i != p) { if (x[s] == cnt%2) { dp[s][0][1] = min(dp[s][0][1], a+abs(dp[i][1][0]-dp[i][1][1])); dp[s][1][1] = a; } else { dp[s][1][1] = min(dp[s][1][1], a+abs(dp[i][1][0]-dp[i][1][1])); dp[s][0][1] = a; } } } dp[s][0][1]++, dp[s][1][1]++; if (node[s].size() == 1 && s != 1) { dp[s][0][0] = x[s] *INT_MAX; dp[s][1][0] = (!x[s])*INT_MAX; dp[s][1][1] = x[s] *INT_MAX+1ll; dp[s][0][1] = (!x[s])*INT_MAX+1ll; } for (auto&z:dp[s]) for(auto&w:z) w = min(w, (int)INT_MAX); } signed main() { cin.tie(0)->sync_with_stdio(0); int n; cin >> n; for (int i = 1; i < n; i++) { int a, b; cin >> a >> b; node[a].push_back(b); node[b].push_back(a); } for (int i = 1; i <= n; i++) cin >> x[i]; dfs(1); // for (int i = 1; i <= n; i++) {cout << i << ": "; // for (auto&z:dp[i]) for(auto&w:z) cout << w << ' '; cout << endl; // } int ans = min(dp[1][0][0], dp[1][0][1]); cout << (ans<INT_MAX?to_string(ans):"impossible") << endl; return 0; } /* 4 10 4 49 22 5 1 2 1 3 2 4 2 5 0 1 0 1 1 5 1 2 2 3 3 4 4 5 0 1 1 1 1 impossible */
#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...