이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll ;
typedef pair<int , int> pii ;
typedef pair<ll , ll> pll ;
#define ps push_back
#define pb pop_back
#define mp make_pair
#define all(x) x.begin() , x.end()
#define sz(x) (int)x.size()
#define debug(a) cout<<"debug: "<<(#a)<<" = "<<a<<'\n'
const ll maxn = 1e5 + 6 , inf = 1e10 +10 ;
ll dp[maxn][5] ;
ll col[maxn] ;
ll n ;
vector<ll > adj[maxn] ;
void dfs(ll v , ll p = -1){
if (sz(adj[v]) == 1 && v != 1){
if (col[v]){
dp[v][2] = 0 ;
dp[v][1] = 1 ;
}
else {
dp[v][0] = 0 ;
dp[v][3] = 1 ;
}
return ;
}
for (ll u : adj[v]){
if (u != p){
dfs(u ,v) ;
}
}
ll mne = inf , sum = 0 ;
ll cnt1 = 0 ;
for (ll u : adj[v]){
if (u == p) continue ;
if (dp[u][1] <= dp[u][0]){
cnt1 ++ ;
sum += dp[u][1] ;
mne = min(mne , (dp[u][0] - dp[u][1])) ;
}
else{
sum += dp[u][0] ;
mne = min(mne , (dp[u][1] - dp[u][0])) ;
}
}
/*debug(v) ;
debug(sum) ;
debug(cnt1) ;
debug(mne) ;
cout << '\n' ;*/
if (col[v]){
if (cnt1 % 2){
dp[v][0] = sum ;
dp[v][2] = sum + mne ;
}
else {
dp[v][2] = sum ;
dp[v][0] = sum + mne ;
}
}
else {
if (cnt1 % 2){
dp[v][2] = sum ;
dp[v][0] = sum + mne ;
}
else {
dp[v][0] = sum ;
dp[v][2] = sum + mne ;
}
}
mne = inf , sum = 0 ;
cnt1 = 0 ;
for (ll u : adj[v]){
if (u == p) continue ;
if (dp[u][3] <= dp[u][2]){
cnt1 ++ ;
sum += dp[u][3] ;
mne = min(mne , (dp[u][2] - dp[u][3])) ;
}
else{
sum += dp[u][2] ;
mne = min(mne , (dp[u][3] - dp[u][2])) ;
}
}
if (col[v]){
if (cnt1 % 2){
dp[v][3] = sum +1;
dp[v][1] = sum + mne +1;
}
else {
dp[v][1] = sum +1;
dp[v][3] = sum + mne +1;
}
}
else {
if (cnt1 % 2){
dp[v][1] = sum +1;
dp[v][3] = sum + mne +1;
}
else {
dp[v][3] = sum +1;
dp[v][1] = sum + mne +1;
}
}
return ;
}
int main()
{
ios::sync_with_stdio(false) ;
cin.tie(NULL) ;
cout.tie(NULL) ;
cin >> n ;
for (int i = 1 ; i <= n-1 ; i++){
ll a , b ;
cin >> a >> b ;
adj[a].ps(b) ;
adj[b].ps(a) ;
}
for (int i = 1 ;i <= n ; i++){
cin >> col[i] ;
}
for (int i = 1 ; i <= n ; i++){
for (int j = 0 ; j < 4 ; j++)
dp[i][j] = inf ;
}
dfs(1) ;
ll ans = min(dp[1][0] , dp[1][1]) ;
if (ans > n){
cout << "impossible\n" ;
return 0 ;
}
cout << ans << '\n' ;
}
# | 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... |