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 "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vpii;
typedef vector<vpii> vvpii;
#define sz(x) (int)(x).size()
#define all(x) (x).begin(), (x).end()
int N;
vvi adj;
vi dpP, dpN;
vi ans_mini;
int miniCheck = 0;
void dfs_mini(int v, int p)
{
if (sz(adj[v]) == 1 && v != p)
{
// leaf
dpN[v] = 0;
dpP[v] = INT_MAX;
return;
}
for (int u : adj[v])
if (u != p)
dfs_mini(u, v);
dpN[v] = 0;
for (int u : adj[v])
if (u != p)
dpN[v] += min(dpP[u], dpN[u] + 2);
for (int u : adj[v])
if (u != p)
{
int tmp = dpN[v] - min(dpP[u], dpN[u] + 2) + min(dpP[u], dpN[u]) + 2;
dpP[v] = min(dpP[v], tmp);
}
}
void reconstruct_dpP(int v, int p);
void reconstruct_dpN(int v, int p, int except);
void reconstruct_dpN(int v, int p, int except = -1)
{
if (sz(adj[v]) == 1 && v != p)
return; // leaf
for (int u : adj[v])
{
if (u == p)
continue;
if (u == except)
{
swap(ans_mini[v], ans_mini[u]);
miniCheck += 2;
if (dpP[u] < dpN[u])
reconstruct_dpP(u, v);
else
reconstruct_dpN(u, v);
}
else if (dpP[u] < dpN[u] + 2)
reconstruct_dpP(u, v);
else
{
swap(ans_mini[v], ans_mini[u]);
miniCheck += 2;
reconstruct_dpN(u, v);
}
}
}
void reconstruct_dpP(int v, int p)
{
if (sz(adj[v]) == 1 && v != p)
return; // leaf
int w = -1;
for (int u : adj[v])
if (u != p)
{
int tmp = dpN[v] - min(dpP[u], dpN[u] + 2) + min(dpP[u], dpN[u]) + 2;
if (dpP[v] == tmp)
{
w = u;
break;
}
}
reconstruct_dpN(v, p, w);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> N;
adj.resize(N);
for (int i = 0, a, b; i < N - 1; ++i)
{
cin >> a >> b, --a, --b;
adj[a].push_back(b), adj[b].push_back(a);
}
dpP.assign(N, INT_MAX), dpN.assign(N, INT_MAX);
dfs_mini(0, 0);
ans_mini.resize(N);
iota(all(ans_mini), 1);
reconstruct_dpP(0, 0);
cout << dpP[0] << " ";
cout << miniCheck << endl;
assert(miniCheck == dpP[0]);
for (int v : ans_mini)
cout << v << " ";
cout << endl;
for (int v : ans_mini)
cout << v << " ";
cout << endl;
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... |