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;
#define ll long long
const int X = 3e5 + 5;
int n, dp[X][2][2];
vector<int> adj[X];
bool vis[X], kondisi[X];
void dfs(int cur) {
vis[cur] = 1;
if(kondisi[cur]) {
dp[cur][1][0] = 1;
dp[cur][0][1] = 0;
} else {
dp[cur][0][0] = 0;
dp[cur][1][1] = 1;
}
for(int nxt: adj[cur]) {
if(vis[nxt]) continue;
dfs(nxt);
// no toggle
int prev_no = dp[cur][0][0], prev_yes = dp[cur][0][1];
// off
dp[cur][0][0] = min(dp[nxt][0][0] + prev_no, dp[nxt][1][0] + prev_yes);
// on
dp[cur][0][1] = min(dp[nxt][0][0] + prev_yes, dp[nxt][1][0] + prev_no);
// toggle
prev_no = dp[cur][1][0], prev_yes = dp[cur][1][1];
dp[cur][1][0] = min(dp[nxt][0][1] + prev_no, dp[nxt][1][1] + prev_yes);
dp[cur][1][1] = min(dp[nxt][0][1] + prev_yes, dp[nxt][1][1] + prev_no);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n;
for(int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i = 1; i <= n; i++) cin >> kondisi[i];
for(int i = 1; i <= n; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
dp[i][j][k] = 1e6;
}
}
}
dfs(1);
if(min(dp[1][1][0], dp[1][0][0]) > n) {
cout << "impossible" << endl;
} else cout << min(dp[1][1][0], dp[1][0][0]) << endl;
return 0;
}
# | 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... |