LittleTree
SRM 386 · 2008-01-05 · by eleusive
Problem Statement
You're given a rooted tree and you wish to perform several augmentation operations on it. An augmentation operation consists of the following steps:
- Choose a non-root vertex V.
- Choose a vertex U, which is an ancestor of V.
- Erase the edge from V to its parent.
- Draw an edge from U to V so that U becomes the parent of V.
If V and U are at levels L1 and L2, respectively, then the cost of the augmentation operation described above is L1 - L2 - 1.
A tree has height K if there exists some vertex at level K and no vertex is at level K+1. Given a tree and an
0 0
\ / \
1 2 1
\ => / \
2 3 4
/ \
3 4 The tree contains exactly N vertices, and is described by a
Constraints
- N will be between 2 and 100, inclusive.
- height will be between 1 and N-1, inclusive.
- edges will be formatted as described in the problem statement.
- edges will contain between 1 and 50 elements, inclusive.
- Each element of edges will contain between 1 and 50 characters, inclusive.
- There will be exactly N-1 tree edges contained in edges.
- edges will represent a tree.
5
{"0,1 1,2 2,3 2,4"}
2
Returns: 1
This is the example from the problem statement.
5
{"0,1 1,2 2,3 2,4"}
1
Returns: 3
The tree is the same from above, but we must get a resulting tree of height 1. One way to achieve this is to augment vertices 3 and 4 to become children of vertex 0, then augment vertex 2 to become a child of vertex 0, for a total cost of 5. However, we can do better by first augmenting the subtree rooted at vertex 2 to become a child of vertex 0, then augmenting vertices 3 and 4 to become children of vertex 0, for a total cost of 3.
3
{"0,1 1,2"}
2
Returns: 0
This tree already has a height of 2, so we don't need to perform any augmentations.
9
{"0,3 3,1 1,8 ","8,","6 2,7 4,2 0,4 7",",5"}
3
Returns: 2
2
{"0,1"}
1
Returns: 0
Submissions are judged against all 91 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class LittleTree with a public method int minCost(int N, vector<string> edges, int height) · 91 test cases · 2 s / 256 MB per case