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;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define vf first
#define vs second
#define ar array
#define all(x) x.begin(),x.end()
const int inf = 0x3f3f3f3f;
const int mod = 1000000007;
const double PI=3.14159265358979323846264338327950288419716939937510582097494459230;
bool remender(ll a , ll b){return a%b;}
const int N = 100003;
vector<int> adj[N];
int dp[N][2][2];
int arr[N];
void dfs(int node , int par = -1){
dp[node][0][0] = dp[node][1][0] = 0;
dp[node][0][1] = dp[node][1][1] = 1;
for(int i : adj[node]){
if(i != par)dfs(i,node);
}
for(int t1 = 0; t1 < 2; t1++){
for(int t2 = 0; t2 < 2; t2++){
int od = 1 - ((t2 + t1) % 2);
int dif = N , dif1 = N , both = 0;
int ans = 0 , cnt = 0;
for(int i : adj[node]){
if(i!=par){
if(dp[i][(arr[i-1] + t2) % 2][0] == dp[i][(arr[i-1] + t2) % 2][1])both++;
else if(dp[i][(arr[i-1] + t2) % 2][0] > dp[i][(arr[i-1] + t2) % 2][1]){
dif = min(dif , dp[i][(arr[i-1] + t2) % 2][0] - dp[i][(arr[i-1] + t2) % 2][1]);
cnt++;
cnt %= 2;
}
else {
dif1 = min(dif1 , dp[i][(arr[i-1] + t2) % 2][1] - dp[i][(arr[i-1] + t2) % 2][0]);
}
ans += min(dp[i][(arr[i-1] + t2) % 2][0] , dp[i][(arr[i-1]+t2)%2][1]);
ans = min(ans , N);
}
}
if(cnt == od && both == 0){
ans += min(dif,dif1);
}
ans = min(ans , N);
dp[node][t1][t2] += ans;
}
}
}
void solve(){
int n;
cin >> n;
for(int i = 0; i < n-1; i++){
int a , b;
cin >> a >> b;
adj[a].pb(b);
adj[b].pb(a);
}
for(int i = 0; i < n; i++)cin >> arr[i];
dfs(1);
int res = min(dp[1][arr[0]][0] , dp[1][arr[0]][1]);
if(res > n){
cout << "impossible\n";
}
else cout << res << '\n';
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//int t;cin >> t;while(t--)
solve();
return 0;
}
# | 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... |