TopCoder problem "PolygonColors" used in SRM 406 (Division II Level Three)

Problem Statement

    Consider a regular polygon with N sides. A diagonal is defined to be a line segment drawn that connects two non-adjacent vertices of the polygon (with the two vertices as its endpoints). A set of diagonals is said to be safe if no two diagonals cross one another, except for possibly at the polygon's vertices.

A coloring of a polygon is a mapping of the non-negative integers, or colors, to the vertices of the polygon. Given a set of safe diagonals, a valid coloring of a polygon is a coloring of the polygon such that no two vertices which are connected by a diagonal or share a side have the same color.

Two diagonals are distinct if at least one of their endpoints is different, and two sets of diagonals are distinct if one set contains some diagonal not contained in the other.

You're given a coloring of a polygon with N sides, where the coloring is given by a int[] colors and N is described by a int. Here, the ith element of colors is the color of the ith vertex. Return how many distinct sets of safe diagonals may be assigned to the polygon such that the coloring is valid. As this result may be very large, return the answer modulo 100000007.


Parameters:int, int[]
Method signature:int getWays(int N, int[] colors)
(be sure your method is public)


-N will be between 3 and 50, inclusive.
-colors will have exactly N elements.
-Each element of colors will be between 0 and N-1, inclusive.


{1, 2, 0}
Returns: 1
There are no diagonals we can add to a triangle, so the empty set is the only possibility.
{1, 2, 3, 0}
Returns: 3
We can either add 0 or 1 diagonals, and there are two ways to add a diagonal.
{0, 1, 1, 1, 1}
Returns: 0
Here we have vertices that share sides, but have the same color. Even if we choose not to add any diagonals, there are no safe sets here.
Returns: 96791474

Problem url:

Problem stats url:




PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem categories:

Dynamic Programming, Math