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
#define ld long double
#define fi first
#define se second
vector<int> adj[100005], depth2[100005];
queue<int> q;
int a[100005], depth1[100005];
bool vis[100005];
ll dp[100005][2][2];
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int n;
cin >> n;
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] = 1e9;
}
}
for (int i = 0; i < n - 1; 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 >> a[i];
q.push(1);
vis[1] = 1;
while (!q.empty()) {
int x = q.front();
q.pop();
for (auto u : adj[x]) {
if (vis[u]) continue;
vis[u] = 1;
depth1[u] = depth1[x] + 1;
q.push(u);
}
}
for (int i = 1; i <= n; i++) {
vis[i] = 0;
depth2[depth1[i]].push_back(i);
if ((i != 1) and ((int)adj[i].size() == 1)) dp[i][0][a[i]] = 0, dp[i][1][1 - a[i]] = 1, vis[i] = 1;
}
for (int i = n - 1; i >= 0; i--) {
for (auto x : depth2[i]) {
if ((x != 1) and ((int)adj[x].size() == 1)) continue;
dp[x][0][a[x]] = 0, dp[x][1][1 - a[x]] = 1, dp[x][0][1 - a[x]] = 1e9, dp[x][1][a[x]] = 1e9;
for (auto u : adj[x]) {
if (!vis[u]) continue;
ll c1 = dp[x][0][0], c2 = dp[x][0][1], c3 = dp[x][1][0], c4 = dp[x][1][1];
dp[x][0][0] = min(c1 + dp[u][0][0], c2 + dp[u][1][0]);
dp[x][0][1] = min(c2 + dp[u][0][0], c1 + dp[u][1][0]);
dp[x][1][0] = min(c3 + dp[u][0][1], c4 + dp[u][1][1]);
dp[x][1][1] = min(c4 + dp[u][0][1], c3 + dp[u][1][1]);
}
vis[x] = 1;
}
}
ll ans = min(dp[1][0][0], dp[1][1][0]);
if (ans > n) cout << "impossible\n";
else cout << ans << "\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... |