#include<bits/stdc++.h>
#define endl '\n'
#define pb push_back
using namespace std;
const int maxn = 1e5 + 10;
void speed()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
int n, a[maxn];
vector < int > g[maxn];
int dp[maxn][2][2];
void dfs(int beg, int from)
{
int sz = 0;
vector < int > v;
for (auto nb: g[beg])
{
if(nb == from)continue;
sz ++;
dfs(nb, beg);
v.pb(nb);
}
if(sz == 0)
{
if(a[beg] == 0)
{
dp[beg][0][0] = 0;
dp[beg][1][1] = 1;
}
else
{
dp[beg][1][0] = 0;
dp[beg][0][1] = 1;
}
/// cout << "* " << beg << endl;
// cout << dp[beg][0][0] << " " << dp[beg][1][0] << endl;
// cout << dp[beg][0][1] << " " << dp[beg][1][1] << endl;
return;
}
// cout << "SOLVING " << beg << endl;
/// solve togged
/// iskam dr da sa 1
//cout << "case 1: togged." << endl;
int sum0 = 0, sum1 = 1e9;
for (auto nb: v)
{
int updsum0 = 1e9, updsum1 = 1e9;
if(dp[nb][1][0] != -1)
{
updsum0 = sum0 + dp[nb][1][0];
updsum1 = sum1 + dp[nb][1][0];
}
if(dp[nb][1][1] != -1)
{
updsum0 = min(updsum0, sum1 + dp[nb][1][1]);
updsum1 = min(updsum1, sum0 + dp[nb][1][1]);
}
sum0 = updsum0;
sum1 = updsum1;
// cout << nb << "::: " << sum0 << " " << sum1 << endl;
}
if(a[beg])
{
dp[beg][0][1] = sum0 + 1;
dp[beg][1][1] = sum1 + 1;
}
else
{
dp[beg][1][1] = sum0 + 1;
dp[beg][0][1] = sum1 + 1;
}
if(dp[beg][1][1] >= 1e9)dp[beg][1][1] = -1;
if(dp[beg][0][1] >= 1e9)dp[beg][0][1] = -1;
/// ne e togged
// cout << "case 2: not togged" << endl;
sum0 = 0;
sum1 = 1e9;
for (auto nb: v)
{
int updsum0 = 1e9, updsum1 = 1e9;
if(dp[nb][0][0] != -1)
{
updsum0 = sum0 + dp[nb][0][0];
updsum1 = sum1 + dp[nb][0][0];
}
if(dp[nb][0][1] != -1)
{
updsum0 = min(updsum0, sum1 + dp[nb][0][1]);
updsum1 = min(updsum1, sum0 + dp[nb][0][1]);
}
sum0 = updsum0;
sum1 = updsum1;
// cout << nb << "::: " << sum0 << " " << sum1 << endl;
}
if(a[beg])
{
dp[beg][0][0] = sum1 ;
dp[beg][1][0] = sum0 ;
}
else
{
dp[beg][1][0] = sum1 ;
dp[beg][0][0] = sum0 ;
}
if(dp[beg][1][0] >= 1e9)dp[beg][1][0] = -1;
if(dp[beg][0][0] >= 1e9)dp[beg][0][0] = -1;
// cout << "* " << beg << endl;
// cout << dp[beg][0][0] << " " << dp[beg][1][0] << endl;
// cout << dp[beg][0][1] << " " << dp[beg][1][1] << endl;
}
int main()
{
speed();
cin >> n;
for (int i = 1; i < n; ++ i)
{
int a, b;
cin >> a >> b;
g[a].pb(b);
g[b].pb(a);
}
for (int i = 1; i <= n; ++ i)
cin >> a[i];
memset(dp, -1, sizeof(dp));
dfs(1, -1);
int res = 1e9;
if(dp[1][0][0] != -1)res = min(res, dp[1][0][0]);
if(dp[1][0][1] != -1)res = min(res, dp[1][0][1]);
if(res == 1e9)cout << "impossible" << endl;
else cout << res << 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... |