이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <vector>
using namespace std;
/*
dp[u][flag1][flag2] = minimum toggles from descendants of u only required such that:
state of u is flag1
state of all direct children of u is flag2
state of all other descendants is 0.
if this is impossible, 1e9;
*/
vector<int> edge[100001];
int sv[100001];
vector<int> p(100001, 0);
vector<int> children[100001];
int dp[100001][2][2];
void dfs1(int u)
{
for(int v: edge[u])
{
if(p[u] == v) continue;
p[v] = u;
children[u].push_back(v);
dfs1(v);
}
}
void dfs2(int u)
{
for(int v: children[u])
dfs2(v);
dp[u][ sv[u] ][0] = dp[u][ sv[u] ][1] = 0;
//dp_curr[u][flag1][flag2] = state of dp assuming it has only previously visited children
for(int v: children[u])
{
int X[2][2];
for(int f = 0; f <= 1; f++)
for(int g = 0; g <= 1; g++)
X[f][g] = min(dp[u][f][g] + dp[v][g][0], dp[u][!f][g] + dp[v][!g][1] + 1);
for(int f = 0; f <= 1; f++)
for(int g = 0; g <= 1; g++)
dp[u][f][g] = X[f][g];
}
// cout << u << ' ' << dp[u][0][0] << ' ' << dp[u][0][1] << ' ' << dp[u][1][0] << ' ' << dp[u][1][1] << '\n';
}
int main()
{
int N;
cin >> N;
for(int i = 1; i <= N-1; i++)
{
int a, b;
cin >> a >> b;
edge[a].push_back(b);
edge[b].push_back(a);
}
edge[1].push_back(0);
edge[0].push_back(1);
dfs1(0);
for(int i = 0; i <= N; i++)
{
for(int f = 0; f <= 1; f++)
for(int g = 0; g <= 1; g++)
dp[i][f][g] = N+1;
}
for(int i = 1; i <= N; i++)
cin >> sv[i];
dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = dp[0][1][1] = 0;
dfs2(0);
int res = min(dp[0][0][0], dp[0][1][0]);
if(res >= N+1) cout << "impossible\n";
else cout << res << '\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... |