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 <iostream>
#include <bits/stdc++.h>
#include <vector>
using namespace std;
using ll = long long;
const int nmax = 1e5 + 9;
const ll inf = 1e7;
vector<int> adj[nmax];
bool on[nmax];
ll dp[2][2][nmax];
void dfs (int nod = 1, int par = 0)
{
ll temp[2][2];
temp[0][0] = 0;
temp[1][0] = 0;
temp[0][1] = inf;
temp[1][1] = inf;
for (auto to : adj[nod])
{
if (to == par) continue;
dfs (to , nod);
ll t[2][2];
t[0][0] = min(temp[0][0] + dp[0][0][to] , temp[0][1] + dp[0][1][to]);
t[1][0] = min (temp[1][0] + dp[1][0][to] , temp[1][1] + dp[1][1][to]);
t[0][1] = min(temp[0][1] + dp[0][0][to] , temp[0][0] + dp[0][1][to]);
t[1][1] = min(temp[1][0] + dp[1][1][to] , temp[1][1] + dp[1][0][to]);
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
temp[i][j] = t[i][j];
}
if (on[nod])
{
dp[0][0][nod] = temp[0][1];
dp[0][1][nod] = 1 + temp[1][0];
dp[1][0][nod] = temp[0][0];
dp[1][1][nod] = 1 + temp[1][1];
}
else {
dp[0][0][nod] = temp[0][0];
dp[0][1][nod] = 1 + temp[1][1];
dp[1][0][nod] = temp[0][1];
dp[1][1][nod] = 1 + temp[1][0];
}
// cout << nod << '\n';
// cout << temp[0][0] << ' ' << temp[0][1] << ' ' << temp[1][0] << ' ' << temp[1][1] << '\n';
// cout << dp[0][0][nod] << ' ' << dp[0][1][nod] << ' ' << dp[1][0][nod] <<
// ' '<< dp[1][1][nod];
// cout << '\n';
}
int main ()
{
int n; cin >> n;
for (int i = 1; i < n; i++)
{
int x, y; cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
for (int i = 1; i <= n; i++)
{
cin >> on[i];
}
dfs();
if (min(dp[0][1][1] , dp[0][0][1]) >= inf) cout << "impossible\n";
else cout << min(dp[0][1][1] , dp[0][0][1]);
}
# | 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... |