Cutting the Ribbon Banner (medium version)
Unlike the easy version (problem 254), the banner may now be cut any number of times, the banner is longer, and you must find the fewest pieces.
A ribbon banner carries a string s of n lowercase English letters. The banner is cut between
neighbouring letters into one or more non-empty pieces, keeping the letters in order, and each piece
must read the same from left to right as from right to left (it must be a palindrome). Making no
cut at all is allowed if the whole banner is already a palindrome.
A single letter is always a palindrome, so cutting between every pair of neighbours always works. Find the smallest possible number of pieces.
Input
The first line contains an integer n (1 ≤ n ≤ 5000), the length of the banner.
The second line contains the string s of exactly n lowercase English letters.
Output
Print one integer: the minimum number of pieces into which the banner can be cut so that every piece is a palindrome.
Notes
In the first example, noonabba is cut once, into noon and abba. The whole banner isn't a
palindrome, so one piece is not enough.
In the second example, abaab can be cut into a and baab. Cutting off the longest palindrome
at the front first, aba, is a trap: the rest, ab, then needs two more pieces, three in total.
In the third example, no two neighbouring letters of abc form a palindrome, so every letter
becomes its own piece.