Codeforces #596 div1 D/div2 F Tree Factory

Topic links: https://codeforces.com/contest/1246/problem/D

The meaning of problems: there are n nodes to a rooted tree, there are requirements for an n nodes bamboo tree structure, each node is a bamboo only one child node, only one node has no child nodes rooted tree. Bamboo can be, if not for the root node v and v is the parent node is not the root, then v and v subtree move operation on a parent node of the parent node v. Each node can customize the number of bamboo, at least ask how many operations will become bamboo tree, bamboo output numbers, the number of operations and manipulate objects of each operation.

Practices: very (write) has (not) Italy (out) think (to) configuration. First, the lower bound is concluded answer n-1-dep (dep depth of the tree), because each point of operation will only make a sub-tree in the depth of -1, i.e. that the maximum of the maximum depth of -1. Consideration Conversely, if given a bamboo with a tree structure to each select a subtree operation to move it downwards along one edge, the number of the mobile must be of n-1-dep, therefore, the operation It is bound to the number of n-1-dep. Construction process, the chain tree deepest node is located on the last, where a reference code DU teachers, very subtle, see the specific implementation code.

Reference Code:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
const int MAXN = 100005;
vector<int> sequence, operation, son[MAXN];
int cnt, heavyson[MAXN], dep[MAXN], father[MAXN], n;

void dfs(int now)
{
    sequence.push_back(now);
    for (int i = 0; i < cnt; ++i)
        operation.push_back(now);
    cnt = 0;
    for (auto v:son[now])
        if (v != heavyson[now])
            dfs(v);
    if (heavyson[now])
        dfs(heavyson[now]);
    cnt++;
}

int main()
{
    cin >> n;
    dep[0] = 1;
    for (int i = 1; i < n; ++i)
    {
        cin >> father[i];
        son[father[i]].push_back(i);
        dep[i] = dep[father[i]] + 1;
    }
    int maxdep = max_element(dep, dep + n) - dep;
    int heavysonnode = maxdep;
    while (heavysonnode)
    {
        heavyson[father[heavysonnode]] = heavysonnode;
        heavysonnode = father[heavysonnode];
    }
    dfs(0);
    for (int i = 0; i < n; ++i)
    {
        if (i != 0)
            cout << " ";
        cout << sequence[i];
    }
    cout << endl;
    cout << (int) operation.size() << endl;
    for (int i = 0; i < (int) operation.size(); ++i)
    {
        if (i != 0)
            cout << " ";
        cout << operation[i];
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/mapleaves/p/11778007.html