#P3816. [FJOI2017] 树的平均路长问题

    ID: 2756 远端评测题 1000ms 250MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>字符串动态规划,dp2017各省省选福建枚举,暴力

[FJOI2017] 树的平均路长问题

Description

The internal path length IPL(T)IPL(T) of a tree TT is defined as:

IPL(T)=vTlength(path(v)),IPL(T)=\sum_{v\in T} length(path(v)),

where vv ranges over the internal nodes of TT, and length(path(v))length(path(v)) is the length of the path from the root to node vv.

A red-black tree is a special binary search tree in which each node is colored red or black. If we regard null pointers in a binary search tree as pointing to an empty node, we call these empty nodes the external nodes of the BST. We stipulate that all external nodes have height 1-1. All nodes other than external nodes are internal nodes.

A red-black tree is a colored binary search tree that satisfies the following red-black properties:

  1. Every node is either red or black.
  2. Every external node is black.
  3. The children of any red node are black.
  4. Every path from any node to its descendant external nodes contains the same number of black nodes.

For any node xx in a red-black tree, the number of black nodes on any path from xx (excluding xx) down to an external node is called the black height of node xx, denoted bh(x)bh(x). The black height of a red-black tree is the black height of its root.

Given a positive integer nn, design an algorithm to compute, among all red-black trees with nn nodes, the maximum possible internal path length.

Input Format

Multiple test cases. Each line contains a single positive integer nn (1n300001\le n\le 30000), which is the number of nodes in the red-black tree. The input is terminated by a line containing a single 00.

Output Format

For each given nn, output the maximum internal path length on a separate line. Do not output any extra content.

1
2
3
0
1
3
5
0

Hint

Translated by ChatGPT 5