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 <bits/stdc++.h>
using namespace std;
using ll = long long;
#define pb emplace_back
#define AI(i) begin(i), end(i)
template<class T> bool chmin(T &a, T b) { return b < a && (a = b, true); }
template<class T> bool chmax(T &a, T b) { return a < b && (a = b, true); }
#ifdef KEV
#define DE(args...) kout("[ " + string(#args) + " ] = ", args)
void kout() { cerr << endl; }
template<class T, class ...U> void kout(T a, U ...b) { cerr << a << ' ', kout(b...); }
template<class T> void debug(T l, T r) { while (l != r) cerr << *l << " \n"[next(l)==r], ++l; }
#else
#define DE(...) 0
#define debug(...) 0
#endif
const int MAX_N = 300010, inf = MAX_N;
int dp[MAX_N][2][2], n, state[MAX_N];
vector<int> edge[MAX_N];
void dfs(int x, int lst) {
for (int u : edge[x]) if (u != lst)
dfs(u, x);
// consider when I don't touch the x'th switch
{
int A[2]{inf, inf}, B[2];
A[ state[x] ] = 0;
for (int u : edge[x]) if (u != lst) {
B[0] = B[1] = inf;
for (int j = 0;j < 2;++j) {
// consider I don't touch both x, u
chmin(B[j], A[j] + dp[u][0][0]);
// consider I touch just u, not x
chmin(B[j^1], A[j] + dp[u][1][0]);
}
swap(A, B);
}
dp[x][0][0] = A[0];
dp[x][0][1] = A[1];
}
// consider when I touch the x'th switch
{
int A[2]{inf, inf}, B[2];
A[ state[x]^1 ] = 1;
for (int u : edge[x]) if (u != lst) {
B[0] = B[1] = inf;
for (int j = 0;j < 2;++j) {
// consider I touch just x, not u
chmin(B[j], A[j] + dp[u][0][1]);
// consider I touch both x, u
chmin(B[j^1], A[j] + dp[u][1][1]);
}
swap(A, B);
}
dp[x][1][0] = A[0];
dp[x][1][1] = A[1];
}
}
int32_t main() {
ios_base::sync_with_stdio(0), cin.tie(0);
cin >> n;
for (int a, b, i = 1;i < n;++i) {
cin >> a >> b;
edge[a].pb(b), edge[b].pb(a);
}
for (int i = 1;i <= n;++i) cin >> state[i];
dfs(1, 1);
int res = min(dp[1][0][0], dp[1][1][0]);
if (res == inf) {
cout << "impossible\n";
} else cout << res << '\n';
}
# | 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... |