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 sp << " " <<
#define int long long
#define vi vector<int>
#define F(xxx,yyy) for (int xxx=1;xxx<=yyy;xxx++)
#define pii pair<int,int>
const int N = 1e5+1;
vi c(N);
vi edges[N];
int dp[N][2][2];
void dfs(int node,int par,int p,int pp) {
if (dp[node][p][pp]!=1e9+5) return;
int tog = c[node]^p^pp;
dp[node][p][pp] = 1e9;
int sm = 0;
vi ones;
for (auto it : edges[node]) {
if (it != par) {
dfs(it,node,0,p);
dfs(it,node,1,p);
sm+=dp[it][0][p];
ones.push_back(dp[it][1][p]-dp[it][0][p]);
}
}
if (!(tog)) dp[node][p][pp] = min(dp[node][p][pp],sm+p);
if (ones.empty()) return;
sort(ones.begin(),ones.end());
for (int i=1;i<(int)ones.size();i++) ones[i]+=ones[i-1];
int sz = ones.size();
for (int i=2-tog;i<=sz;i+=2) {
dp[node][p][pp] = min(dp[node][p][pp],sm+ones[i-1]+p);
}
}
void solve() {
int n;
cin >> n;
memset(dp,-1,sizeof dp);
F(i,n-1) {
int a,b;
cin >> a >> b;
edges[a].push_back(b);
edges[b].push_back(a);
}
F(i,n) cin >> c[i];
F(i,n) {
for (int j=0;j<2;j++) {
for (int k=0;k<2;k++) {
dp[i][j][k] = 1e9+5;
}
}
}
dfs(1,1,1,0);
dfs(1,1,0,0);
F(i,n) {
for (int j=0;j<2;j++) {
for (int k=0;k<2;k++) {
//cout << i sp j sp k sp dp[i][j][k] << endl;
}
}
}
int x = min(dp[1][0][0],dp[1][1][0]);
cout << (x>=1e9?"impossible":to_string(x)) << endl;
}
signed main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#ifdef Local
freopen("in","r",stdin);
freopen("out","w",stdout);
#endif
int t = 1;
//cin >> t;
F(i,t) solve();
}
# | 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... |