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>
#define ll int
#define ld long double
#define fs first
#define sc second
#define debug(y) cout<<y,exit(0)
using namespace std;
typedef pair<ll,ll> LL;
const ll N = 1e5 + 9;
const ll inf = 1e9 + 7;
vector<ll> g[N];
ll n,x,y,a[N],dp[N][4];
bool chk(ll x,ll i){
return (x >> i) & 1;
}
void Combine(ll u,ll v){
ll tmp[4]; tmp[0] = tmp[1] = tmp[2] = tmp[3] = inf;
for (ll i = 0;i < 4;i++)
for (ll j = 0;j < 4;j++){
if (chk(i,0) && !chk(j,1)) continue;
if (!chk(i,0) && chk(j,1)) continue;
ll now = chk(i,1) ^ chk(j,0); now = now*2 + chk(i,0);
tmp[now] = min(tmp[now],dp[u][i] + dp[v][j]);
}
for (ll i = 0;i < 4;i++) dp[u][i] = tmp[i];
}
void DFS(ll u,ll p){
dp[u][a[u]*2] = 0; dp[u][(1^a[u])*2 + 1] = 1;
for (auto i : g[u]) if (i != p){
DFS(i,u); Combine(u,i);
}
}
int main(){
ios_base::sync_with_stdio(NULL); cin.tie(0); cout.tie(0);
#define task "tst"
if (fopen(task".inp","r")){
freopen(task".inp","r",stdin);
//freopen(task".out","w",stdout);
}
cin>>n;
for (ll i = 1;i < n;i++){
cin>>x>>y;
g[x].push_back(y); g[y].push_back(x);
}
for (ll i = 1;i <= n;i++){
cin>>a[i];
for (ll j = 0;j < 4;j++) dp[i][j] = inf;
}
DFS(1,0);
ll kq = min(dp[1][0],dp[1][1]);
if (kq == inf) cout<<"impossible";
else cout<<kq;
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/
Compilation message (stderr)
xanadu.cpp: In function 'int main()':
xanadu.cpp:42:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
42 | freopen(task".inp","r",stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
# | 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... |