This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
using namespace std;
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include <memory.h>
typedef long long LL;
typedef pair<int,int> pii;
#define F first
#define S second
#define mkp make_pair
#define iter(x) x.begin(),x.end()
#define MEM(s,e) memset(s,e,sizeof(s))
const int maxn = 1e5+100,inf = 1e9;
int dp[maxn][2][2]; //index, t/f, on/off
bool status[maxn];
vector <int> adj[maxn];
void dfs(int x,int fr){
int ldp[2][2][2],c=0;
for (auto s:adj[x]) if (s != fr){
dfs(s,x);
for (int i=0;i<2;++i) for (int j=0;j<2;++j){
ldp[c][i][j] = dp[s][i][j];
}
++c;
}
if (!c){
if (status[x]){
dp[x][1][0] = 0;
dp[x][0][1] = 1;
dp[x][0][0] = inf;
dp[x][1][1] = inf;
}
else{
dp[x][0][0] = 0;
dp[x][1][1] = 1;
dp[x][1][0] = inf;
dp[x][0][1] = inf;
}
}
else if (c == 1){
if (status[x]){
dp[x][0][0] = ldp[0][0][1];
dp[x][0][1] = ldp[0][1][0] + 1;
dp[x][1][0] = ldp[0][0][0];
dp[x][1][1] = ldp[0][1][1] + 1;
}
else{
dp[x][0][0] = ldp[0][0][0];
dp[x][0][1] = ldp[0][1][1] + 1;
dp[x][1][0] = ldp[0][0][1];
dp[x][1][1] = ldp[0][1][0] + 1;
}
}
else{
if (status[x]){
dp[x][0][0] = min(inf,min(ldp[0][0][1] + ldp[1][0][0],ldp[0][0][0] + ldp[1][0][1]));
dp[x][0][1] = min(inf,min(ldp[0][1][0] + ldp[1][1][0],ldp[0][1][1] + ldp[1][1][1]) + 1);
dp[x][1][0] = min(inf,min(ldp[0][0][0] + ldp[1][0][0],ldp[0][0][1] + ldp[1][0][1]));
dp[x][1][1] = min(inf,min(ldp[0][1][1] + ldp[1][1][0],ldp[0][1][0] + ldp[1][1][1]) + 1);
}
else{
dp[x][0][0] = min(inf,min(ldp[0][0][0] + ldp[1][0][0],ldp[0][0][1] + ldp[1][0][1]));
dp[x][0][1] = min(inf,min(ldp[0][1][1] + ldp[1][1][0],ldp[0][1][0] + ldp[1][1][1]) + 1);
dp[x][1][0] = min(inf,min(ldp[0][0][1] + ldp[1][0][0],ldp[0][0][0] + ldp[1][0][1]));
dp[x][1][1] = min(inf,min(ldp[0][1][0] + ldp[1][1][0],ldp[0][1][1] + ldp[1][1][1]) + 1);
}
}
}
int main(){
int n;
cin >> n;
for (int _=n-1;_--;){
int u,v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i=1;i<=n;++i) cin >> status[i];
for (int i=1;i<=n;++i) if (adj[i].size() == 1){
dfs(i,0);
int ans = min(dp[i][0][0],dp[i][0][1]);
if (ans >= inf) cout << "impossible\n";
else cout << ans << '\n';
break;
}
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... |