이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 5;
const int INF = 1e9;
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;
}
for(int k = 0 ; k < 2 ; k++){
int sum = 0 , summ = 0 , cnt = 0 , ch = 0;
for(int i : g[ver]){
if(i == par) continue;
int mn = min(dp[i][k][0] , dp[i][k][1]);
sum += mn;
if(dp[i][k][0] == dp[i][k][1]) ch = 1;
if(mn == dp[i][k][1]) cnt++;
}
summ = INF;
for(int i : g[ver]){
if(i == par) continue;
summ = min(summ , sum - min(dp[i][k][0] , dp[i][k][1]) + max(dp[i][k][0] , dp[i][k][1]));
}
if(ch){
dp[ver][0][k] = dp[ver][1][k] = sum;
continue;
}
if(k == 1){
dp[ver][sit[ver]][k] = (cnt & 1 ? sum : summ) + 1;
dp[ver][sit[ver] ^ 1][k] = (cnt & 1 ? summ : sum) + 1;
}
else{
dp[ver][sit[ver]][k] = (cnt & 1 ? summ : sum);
dp[ver][sit[ver] ^ 1][k] = (cnt & 1 ? sum : summ);
}
}
}
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);
}
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;
for(int i = 0 ; i < n ; i++)
if((int)g[i].size() > 1)
root = i;
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... |