problems / 266

Cutting the Ribbon Banner (medium version)

medium strings palindromes dp 1400 ms · 256 MB

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.

Example 1

Input

8
noonabba

Output

2

Example 2

Input

5
abaab

Output

2

Example 3

Input

3
abc

Output

3

Hints · reveal one at a time if you're stuck

Hint 1

Cutting off the longest palindrome at the front doesn't always work (try abaab). Think about the last piece instead: if it is s[j+1..i], what must be true of the letters before it?

Hint 2

Let dp[i] be the fewest pieces for the first i letters, and build it from shorter prefixes by choosing where the last palindromic piece starts. Testing each candidate piece letter by letter, though, is O(n³) in the worst case (think of a banner of equal letters), too slow for n = 5000.

Hint 3

Work out which substrings are palindromes before the DP, in O(n²) total, so each DP step is an O(1) check. Every palindrome has a centre (a letter or the gap between two letters) and can be grown outward from it. This is dynamic programming over prefixes.

report an issue Prefer your own editor? sooks prep 266 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.