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;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef pair<int,int> pi;
typedef vector<pi> pii;
typedef tuple<int,int,int> tii;
typedef vector<ll> li;
typedef vector<li> lii;
#define REP(i,a,b) for(int i=a;i<b;i++)
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define LSOne(s) ((s)&(-s))
ll INF=1e18+10;
ll inf=1e9+10;
ll M=1e9+7;
int n;
vii a;
vector<vector<vector<ll>>> dp;
vi p,b;
void solve(int node){
ll o1=inf,o2=inf,e1=0,e2=0;
for(auto u:a[node]){
if(p[node]==u)continue;
p[u]=node;
solve(u);
ll o1t=min(o1+dp[0][1][u],e1+dp[1][1][u]);
ll o2t=min(o2+dp[0][0][u],e2+dp[1][0][u]);
ll e1t=min(e1+dp[0][1][u],o1+dp[1][1][u]);
ll e2t=min(e2+dp[0][0][u],o2+dp[1][0][u]);
o1=o1t;o2=o2t;e1=e1t;e2=e2t;
}
if(b[node]==0){
dp[0][0][node]=e2;
dp[1][0][node]=1+o1;
dp[1][1][node]=1+e1;
dp[0][1][node]=o2;
}
else{
dp[0][0][node]=o2;
dp[1][0][node]=1+e1;
dp[1][1][node]=1+o1;
dp[0][1][node]=e2;
}
}
int main() {
//ios::sync_with_stdio(0);
//cin.tie(0);
//freopen("test_input.txt", "r", stdin);
//freopen("test_output.txt", "w", stdout);
cin>>n;
a.resize(n);p.resize(n,-1);b.resize(n);
dp.resize(2,vector<vector<ll>>(2,vector<ll>(n)));
REP(i,0,n-1){
int x,y;
cin>>x>>y;
x--;y--;
a[x].PB(y);
a[y].PB(x);
}
REP(i,0,n)cin>>b[i];
solve(0);
ll ans=min(dp[0][0][0],dp[1][0][0]);
if(ans>=inf)cout<<"impossible";
else cout<<ans;
}
# | 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... |