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;
const int MXN = 1e5+5;
const int INF = 1e6;
int n;
vector<int> Adj[MXN];
bool On[MXN];
// off/on, not clicked/clicked
ll dp[MXN][2][2];
void dfs(int u, int p)
{
if(Adj[u].size() <= (p != -1)) {
//cerr << u << " leaf\n";
// leaf
dp[u][On[u]][0] = 0;
dp[u][!On[u]][1] = 1;
return;
}
// all off/on, even clicked/odd clicked
ll sub[2][2][2] = {};
int fr = 1, to = 0;
bool first = true;
//cerr << u << ":\n";
for(int v : Adj[u]) {
if(v == p)
continue;
dfs(v, u);
for(int i = 0; i < 4; i++) {
sub[to][i&1][(i&2)>>1] = INF;
}
if(first) {
for(int i = 0; i < 4; i++) {
sub[to][i&1][(i&2)>>1] = dp[v][i&1][(i&2)>>1];
}
first = false;
swap(fr, to);
continue;
}
// cerr << "from:\n";
// for(int i = 0; i < 4; i++) {
// cerr << sub[fr][(i&2)>>1][i&1] << " ";
// }
// cerr << "\n";
// off, not clicked
sub[to][0][0] = min(sub[to][0][0], sub[fr][0][0] + dp[v][0][0]);
sub[to][0][1] = min(sub[to][0][1], sub[fr][0][1] + dp[v][0][0]);
// off, clicked
sub[to][0][0] = min(sub[to][0][0], sub[fr][0][1] + dp[v][0][1]);
sub[to][0][1] = min(sub[to][0][1], sub[fr][0][0] + dp[v][0][1]);
// on, not clicked
sub[to][1][0] = min(sub[to][1][0], sub[fr][1][0] + dp[v][1][0]);
sub[to][1][1] = min(sub[to][1][1], sub[fr][1][1] + dp[v][1][0]);
// on, clicked
sub[to][1][0] = min(sub[to][1][0], sub[fr][1][1] + dp[v][1][1]);
sub[to][1][1] = min(sub[to][1][1], sub[fr][1][0] + dp[v][1][1]);
// cerr << "to:\n";
// for(int i = 0; i < 4; i++) {
// cerr << sub[to][(i&2)>>1][i&1] << " ";
// }
// cerr << "\n";
swap(fr, to);
}
// all are off, don't click
dp[u][On[u]][0] = sub[fr][0][0];
dp[u][!On[u]][0] = sub[fr][0][1];
// all are on, click
dp[u][!On[u]][1] = 1+sub[fr][1][0];
dp[u][On[u]][1] = 1+sub[fr][1][1];
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for(int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
a--, b--;
Adj[a].push_back(b);
Adj[b].push_back(a);
}
for(int i = 0; i < n; i++) {
cin >> On[i];
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < 4; j++) {
dp[i][j&1][(j&2)>>1] = INF;
}
}
dfs(0, -1);
// for(int i = 0; i < n; i++) {
// cerr << i << ":\n";
// for(int j = 0; j < 4; j++) {
// cerr << " " << dp[i][(j&2)>>1][j&1];
// }
// cerr << "\n";
// }
ll ans = min(dp[0][0][0], dp[0][0][1]);
if(ans >= INF) {
cout << "impossible\n";
}
else {
cout << ans << "\n";
}
return 0;
}
/*
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
*/
# | 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... |