Tree Allocation
Time limit10sMemory limit64 MB
Partition the nodes into blocks of at most B to minimize the worst root-to-leaf block count, for every choice of root.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Tree, Greedy
- Solved
- No attempts yet
Problem
A tree is one of the most widely used data structures in computer science. The structure itself is simple, but it does not fit the way a computer stores data. Memory behaves like a one dimensional array, and a tree is not one dimensional, so cache efficiency becomes a problem once the tree is placed in memory. Data that sits in the cache is read faster, so consider an allocation with good cache behaviour.
The cost of an allocation is defined as follows. Memory is split into blocks, and one block stores at most nodes of the tree. Reading data in a block brings the whole block into the cache, and every piece of data in that block is then read faster. The cost of reading node right after node is when and are in the same block, and otherwise. The cache starts empty, so the first node read on a path always costs . The cost of the path is the sum of the costs of reading those nodes in that order. The cost of an allocation of a tree is the maximum cost over the paths that run from the root to each terminal node. A terminal node is a node with no child under the chosen root, and in a tree with a single node the root itself is the terminal node.
The figure below shows two allocations of a tree with 10 nodes when and node 1 is the root. Each frame is one block. The allocation on the left costs and is not optimal. The allocation on the right reaches the optimal cost .

Given a tree, compute the minimum cost of allocation when node is the root, for every node .
Input
The input contains several test cases. The first line of each test case has two integers and separated by a single space (, ). Each of the next lines contains one integer. The -th integer () means that node and node are connected. The nodes are numbered from to .
The last test case is followed by a line containing two zeros. That line is not a test case.
Output
For each test case, print Case x: on its own line, where is the test case number starting from . Then print lines. The -th line contains the minimum cost of allocation of the given tree when node is the root.