#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
vector<vector<int>> g(100000);
vector<int> are(100000);
vector<vector<vector<int>>> on(100000,vector<vector<int>>(2,vector<int>(2,0)));
pair<int,int> beo(vector<pair<int,int>> &u) {
vector<pair<int,int>> d;
d.reserve(u.size());
int sum = 0;
for (int i = 0; i < u.size(); ++i) {
d.emplace_back(u[i].second-u[i].first,i);
sum+=u[i].first;
}
if(d.size()>0)sort(d.begin(),d.end());
int be=sum,bo=2e5;
for (int i = 0; i < d.size(); ++i) {
sum+=d[i].first;
if(i%2==1) be=min(be,sum);
else bo = min(bo,sum);
}
return {be,bo};
}
int check(bool ch,bool me, bool p, vector<vector<vector<int>>> &t) {
vector<pair<int,int>> d;
int v = me ? 1 : 0;
d.reserve(t.size());
for (auto & i : t) {
d.emplace_back(i[0][v],i[1][v]);
}
auto [e,o] = beo(d);
bool a = me^p^ch;
if(a) return o;
else return e;
}
bool dfs(int cur, int per) {
vector<vector<vector<int>>> t;
for (int i: g[cur]) {
if(i==per) continue;
dfs(i,cur);
t.push_back(on[i]);
}
on[cur][0][0]=check(are[cur],false,false,t);
on[cur][1][0]=check(are[cur],true,false,t)+1;
on[cur][0][1]=check(are[cur],false,true,t);
on[cur][1][1]=check(are[cur],true,true,t)+1;
}
int main() {
cin>>n;
for (int i = 0; i < n-1; ++i) {
int x; int y; cin>>x>>y; x--; y--;
g[x].push_back(y);
g[y].push_back(x);
}
for (int i = 0; i < n; ++i) {
int a; cin>>a;
are[i]=a;
}
dfs(0,-1);
int res = min(on[0][0][0],on[0][1][0]);
if(res>n) {
cout<<"impossible"<<endl;
}else {
cout<<res<<endl;
}
}
Compilation message (stderr)
xanadu.cpp: In function 'bool dfs(int, int)':
xanadu.cpp:49:1: warning: no return statement in function returning non-void [-Wreturn-type]
49 | }
| ^
# | 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... |