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) {
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]);
}
}
dp[node][p][pp] = min(dp[node][p][pp],sm+p);
if (pp^p^c[node] && ones.empty()) dp[node][p][pp] = 1e9;
if (ones.empty()) return;
sort(ones.begin(),ones.end());
for (int i=1;i<ones.size();i++) ones[i]+=ones[i-1];
int tog = (pp^p^c[node]);
int sz = ones.size();
for (int i=max(2LL,tog);i<=sz;i+=2) {
dp[node][p][pp] = min(dp[node][p][pp],sm+ones[i-1]+p+i);
}
}
void solve() {
int n;
cin >> n;
F(i,n) {
for (int j=0;j<2;j++) {
for (int k=0;k<2;k++) dp[i][j][k] =1e9;
}
}
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];
dfs(1,1,0,1);
dfs(1,1,0,0);
int x = min(dp[1][0][0],dp[1][0][1]);
cout << (x==1e9?"impossible\n":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();
}
Compilation message (stderr)
xanadu.cpp: In function 'void dfs(long long int, long long int, long long int, long long int)':
xanadu.cpp:29:17: warning: comparison of integer expressions of different signedness: 'long long int' and 'std::vector<long long int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
29 | for (int i=1;i<ones.size();i++) ones[i]+=ones[i-1];
| ~^~~~~~~~~~~~
# | 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... |