This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#ifndef Local
#pragma GCC optimize("O3,unroll-loops")
const int lim=1e5+100;
#else
const int lim=1e3;
#endif
#include "bits/stdc++.h"
using namespace std;
#define int long long
#define pb push_back
const int mod=1e9+7;
using pii=pair<int,int>;
bool types[lim];
vector<int>v[lim];
int dp[lim][2][2];
bool vis[lim][2][2];
void dfs(int node,int parent,bool clickpar,bool clicknode){
if(vis[node][clickpar][clicknode])return;
vis[node][clickpar][clicknode]=1;
dp[node][clickpar][clicknode]=clicknode;
bool cur=types[node]^clickpar^clicknode;
vector<int>pos;
for(int j:v[node]){
if(j!=parent){
dfs(j,node,clicknode,0),dfs(j,node,clicknode,1);
dp[node][clickpar][clicknode]+=dp[j][clicknode][0];
pos.pb(dp[j][clicknode][1]-dp[j][clicknode][0]);
}
}
sort(pos.begin(),pos.end());
int i=0;
if(cur==1){
if(!pos.size()){
dp[node][clickpar][clicknode]=INT_MAX;
return;
}
dp[node][clickpar][clicknode]+=pos[i++];
}
for(;i+1<pos.size();i+=2){
if(pos[i]+pos[i+1]<0){
dp[node][clickpar][clicknode]+=pos[i]+pos[i+1];
}else{
break;
}
}
}
inline void solve(){
int n;
cin>>n;
for(int i=0;i<n-1;i++){
int x,y;
cin>>x>>y;
v[x].pb(y);
v[y].pb(x);
}
for(int i=1;i<=n;i++){
cin>>types[i];
}
dfs(1,-1,0,0);
dfs(1,-1,0,1);
int ans=min(dp[1][0][0],dp[1][0][1]);
if(n<ans)cout<<"impossible\n";
else cout<<ans<<"\n";
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
#ifdef Local
freopen(".in","r",stdin);
freopen(".out","w",stdout);
#else
//freopen("grass.in","r",stdin);
//freopen("grass.out","w",stdout);
#endif
int t=1;
//cin>>t;
while (t--)
{
solve();
}
}
Compilation message (stderr)
xanadu.cpp: In function 'void dfs(long long int, long long int, bool, bool)':
xanadu.cpp:44:13: 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]
44 | for(;i+1<pos.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... |