이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 5;
const int INF = 1e12;
vector<int> g[N];
int dp[N][2][2] , sit[N] , root , n;
void dfs(int ver , int par){
for(int i : g[ver]){
if(i == par) continue;
dfs(i , ver);
}
if((int)g[ver].size() == 1){
dp[ver][sit[ver]][0] = 0;
dp[ver][sit[ver] ^ 1][1] = 1;
return;
}
int sum1 = 0 , sum2 = 0 , cnt1 = 0 , cnt2 = 0 , rem1 = INF , rem2 = INF;
for(int i : g[ver]){
if(i == par) continue;
sum1 += min(dp[i][0][1] , dp[i][0][0]);
sum2 += min(dp[i][1][1] , dp[i][1][0]);
rem1 = min(rem1 , max(dp[i][0][1] , dp[i][0][0]) - min(dp[i][0][1] , dp[i][0][0]));
rem2 = min(rem2 , max(dp[i][1][1] , dp[i][1][0]) - min(dp[i][1][1] , dp[i][1][0]));
if(dp[i][0][1] <= dp[i][0][0]) cnt1++;
if(dp[i][1][1] <= dp[i][1][0]) cnt2++;
}
for(int k = 0 ; k < 2 ; k++){
if(k == 1){
dp[ver][sit[ver]][k] = min(dp[ver][sit[ver]][k] , sum2 + (cnt2 & 1 ? 0 : rem2) + 1);
dp[ver][sit[ver] ^ 1][k] = min(dp[ver][sit[ver] ^ 1][k] , sum2 + (cnt2 & 1 ? rem2 : 0) + 1);
}
else{
dp[ver][sit[ver]][k] = min(dp[ver][sit[ver]][k] , sum1 + (cnt1 & 1 ? rem1 : 0));
dp[ver][sit[ver] ^ 1][k] = min(dp[ver][sit[ver] ^ 1][k] , sum1 + (cnt1 & 1 ? 0 : rem1));
}
}
}
int32_t main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 0 ; i < n - 1 ; i++){
int u , v;
cin >> u >> v;
u--;
v--;
g[u].push_back(v);
g[v].push_back(u);
if((int)g[v].size() > 1) root = v;
if((int)g[u].size() > 1) root = u;
}
for(int i = 0 ; i < n ; i++)
cin >> sit[i];
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < 2 ; j++)
for(int k = 0 ; k < 2 ; k++)
dp[i][j][k] = INF;
dfs(root , -1);
int ans = min(dp[root][0][1] , dp[root][0][0]);
if(ans > n) cout << "impossible" << '\n';
else cout << ans << '\n';
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... |