Magic Castle
InterviewTime limit2sMemory limit1024 MB
Given a triangulation of a regular n-gon, find the minimum number of diagonals to remove so that every triangle loses at least one side.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Tree, Graph
- Solved
- No attempts yet
Problem
Newt Salamander spent a long time searching before he found Grindelwald's hideout, where he keeps all his secrets. At the entrance stands a complex magic castle protected by a spell. The castle is a regular -gon, and its vertices are numbered clockwise.
The spell on the castle consists of magic links that triangulate the polygon. They split it into triangles whose vertices are polygon vertices. The triangles do not overlap, and together they cover the whole polygon. For example, a regular hexagon can be linked in several ways, as shown in the picture below.

Links that split the polygon into triangles are considered the strongest. To break the spell, Newt must first destroy every triangle. The Rictusempra spell can destroy one magic link that joins two vertices of the polygon in a single cast. Newt has little time, because a protective spell will soon seal the entrance forever. Find the minimum number of Rictusempra casts needed to destroy all triangles in the castle.
Input
The first line contains , the number of vertices of the regular polygon (). Each of the next lines contains two integers and separated by a space, the vertices joined by the i-th magic link (). The links are guaranteed to form a triangulation of the polygon into triangles whose vertices are vertices of the given -gon.
Output
Print one line with the minimum number of Rictusempra casts needed to destroy all triangles in the castle.
Hint
In the first example, it is enough to destroy the magic links joining vertices (2, 4) and (2, 6). In the second example, all three magic links must be destroyed.