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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
typedef long long ll;
using namespace std;
using namespace __gnu_pbds;
template<class x>
using ordered_set = tree<x, null_type,less<x>, rb_tree_tag,tree_order_statistics_node_update>;
ll mod=(ll)1e9+7;
ll mod1=998244353;
///the defines :)
#define endl '\n'
#define vi vector<int>
#define ent(arr) for(int i=0;i<arr.size();i++)cin>>arr[i];
#define all(arr) arr.begin(),arr.end()
#define allr(arr) arr.rbegin(),arr.rend()
#define sz size()
#define int long long
int dp[200002][2][2];
int n;
vi arr;
vector<vi>adj;
int dfs(int node,int parent,int tg,int cur)
{
int pog=arr[node]^tg^cur;
// cout<<node<<" "<<parent<<" "<<pog<<endl;
if(dp[node][tg][cur]!=-1)return dp[node][tg][cur];
if(parent&&adj[node].sz==1)return (pog?1e9:cur);
//odds and even thingies depending on pog, (i forgor)
int x=adj[node].sz;
int newdp[x+2][2];
memset(newdp,1e9,sizeof newdp);
for(int i=0;i<=x+1;i++)newdp[i][0]=newdp[i][1]=1e9;
newdp[0][pog]=cur;
int cnt=0;
vector<pair<int,int>>xd;
xd.push_back({0,0});
for(auto i:adj[node])
{
if(i==parent)continue;
cnt++;
int e=dfs(i,node,cur,1),e1=dfs(i,node,cur,0);
for(int j=0;j<2;j++)
newdp[cnt][j]=min(newdp[cnt-1][j^1]+e,newdp[cnt-1][j]+e1);
}
/* cout<<node<<" "<<parent<<" "<<pog<<" "<<tg<<" "<<cur<<" "<<newdp[xd.sz][0]<<endl;
for(int i=0;i<xd.sz;i++)
{
cout<<newdp[i][0]<<" "<<newdp[i][1]<<endl;
}
for(auto i:xd)cout<<i.first<<" "<<i.second<<endl;
cout<<"---"<<endl;
*/
return dp[node][tg][cur]=newdp[cnt][0];
}
void preprocess() {}
void solve()
{
cin>>n;
adj.resize(n+1);
arr.resize(n+1);
for(int i=0;i<n-1;i++)
{
int a,b;
cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
memset(dp,-1,sizeof dp);
for(int i=1;i<=n;i++)cin>>arr[i];
int x=min(dfs(1,0,0,1),dfs(1,0,0,0));
if(x>=1e9)cout<<"impossible"<<endl;
else cout<<x<<endl;
}
signed main()
{
// freopen("meta_game_input.txt","r",stdin);
// freopen("otput.txt","w",stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
preprocess();
//bla();
int t=1;
//cin>>t;
while(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... |