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 int long long
const int N = 1e5 + 3;
int dp[N][2][2];
int a[N];
vector<int> vec[N];
void dfs(int v, int p)
{
if(vec[v].size() == 1)
{
dp[v][a[v]][0] = 0;
dp[v][1 - a[v]][1] = 1;
dp[v][a[v]][1] = 1e6;
dp[v][1 - a[v]][0] = 1e6;
return;
}
for(int to : vec[v])
if(to != p)
dfs(to, v);
int mn = 0, par = a[v], mnadd = 1e9;
for(int to : vec[v])
{
if(to == p)
continue;
if(dp[to][0][0] < dp[to][0][1])
{
mn += dp[to][0][0];
mnadd = min(mnadd, dp[to][0][1] - dp[to][0][0]);
}
else
{
mn += dp[to][0][1];
mnadd = min(mnadd, dp[to][0][0] - dp[to][0][1]);
par = 1 - par;
}
}
dp[v][par][0] = mn;
dp[v][1 - par][0] = mn + mnadd;
mn = 0, par = a[v], mnadd = 1e9;
for(int to : vec[v])
{
if(to == p)
continue;
if(dp[to][1][0] < dp[to][1][1])
{
mn += dp[to][1][0];
mnadd = min(mnadd, dp[to][1][1] - dp[to][1][0]);
}
else
{
mn += dp[to][1][1];
mnadd = min(mnadd, dp[to][1][0] - dp[to][1][1]);
par = 1 - par;
}
}
dp[v][1 - par][1] = mn + 1;
dp[v][par][1] = mn + mnadd + 1;
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i = 0; i < n - 1; i ++)
{
int u, v;
cin >> u >> v;
vec[u].push_back(v);
vec[v].push_back(u);
}
for(int i = 1; i <= n; i ++)
cin >> a[i];
int root = 0;
for(int i = 1; i <= n; i ++)
if(vec[i].size() > 1)
root = i;
dfs(root, root);
int ans = min(dp[root][0][0], dp[root][0][1]);
if(ans <= n)
cout << ans;
else
cout << "impossible";
}
# | 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... |