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 N 100010
#define inf 1e6
#define int long long
using namespace std;
int n;
vector <int> g[N];
int v[N];
int dp[N][2][2];
queue <int> topsort;
void solve(int node, int p, int ap, int app){
if(dp[node][ap][app] != inf) return;
vector <int> vl;
int sum = 0;
if(ap == 1) sum++;
for(auto x : g[node]){
if(x == p) continue;
vl.push_back(-dp[x][0][ap] + dp[x][1][ap]);
sum += dp[x][0][ap];
}
int valor = v[node] + ap + app;
valor %= 2;
sort(vl.begin(), vl.end());
if(valor == 0){
dp[node][ap][app] = min(dp[node][ap][app], sum);
for(int i = 1;i < vl.size();i += 2){
sum += vl[i] + vl[i-1];
dp[node][ap][app] = min(dp[node][ap][app], sum);
}
return;
}
else{
if(vl.size() == 0) return;
sum += vl[0];
dp[node][ap][app] = min(dp[node][ap][app], sum);
for(int i = 2;i < vl.size();i += 2){
sum += vl[i] + vl[i-1];
dp[node][ap][app] = min(dp[node][ap][app], sum);
}
return;
}
}
int deg[N];
int pai[N];
void dfs(int node, int p){
pai[node] = p;
for(auto x : g[node]){
if(x == p) continue;
dfs(x, node);
}
}
int32_t main(){
ios::sync_with_stdio(false); cin.tie(0);
cin >> n;
for(int i = 1;i < n;i++){
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
deg[1]++;
for(int i = 1;i <= n;i++) {dp[i][0][0] = dp[i][1][0] = dp[i][0][1] = dp[i][1][1] = inf; cin >> v[i]; deg[i] += g[i].size()-1; if(deg[i] == 0) topsort.push(i);}
dfs(1, 1);
while(!topsort.empty()){
int x = topsort.front();
topsort.pop();
solve(x, pai[x], 0, 0);
solve(x, pai[x], 1, 0);
solve(x, pai[x], 0, 1);
solve(x, pai[x], 1, 1);
deg[pai[x]]--;
if(deg[pai[x]] == 0) topsort.push(pai[x]);
}
int res = min(dp[1][1][0], dp[1][0][0]);
if(res >= N) cout << "impossible\n";
else cout << res << '\n';
return 0;
}
Compilation message (stderr)
xanadu.cpp: In function 'void solve(long long int, long long int, long long int, long long int)':
xanadu.cpp:33:25: 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]
33 | for(int i = 1;i < vl.size();i += 2){
| ~~^~~~~~~~~~~
xanadu.cpp:46:25: 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]
46 | for(int i = 2;i < vl.size();i += 2){
| ~~^~~~~~~~~~~
# | 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... |