Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color c_{i}. The goal of the game is to destroy all the gemstones in the line as quickly as possible.

In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?

Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.


-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones.

The second line contains n space-separated integers, the i-th of which is c_{i} (1 ≤ c_{i} ≤ n) — the color of the i-th gemstone in a line.


-----Output-----

Print a single integer — the minimum number of seconds needed to destroy the entire line.


-----Examples-----
Input
3
1 2 1

Output
1

Input
3
1 2 3

Output
3

Input
7
1 4 4 2 3 2 1

Output
2



-----Note-----

In the first sample, Genos can destroy the entire line in one second.

In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.

In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

Difficulty: HARD

Solutions:
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
n = int(input())
b = list(map(int, input().split()))
dp = [[float('inf') for j in range(n)] for i in range(n)]
for i in range(n):
	dp[i][i] = 1
i = n - 1
while i >= 0:
	j = i + 1
	while j < n:
		dp[i][j] = min(dp[i][j], 1 + dp[i + 1][j])
		k = j
		while k > i:
			if b[i] == b[k]:
				val1 = 1
				if k - 1 >= i + 1:
					val1 = dp[i + 1][k - 1]
				val2 = 0
				if k + 1 <= j:
					val2 = dp[k + 1][j]
				dp[i][j] = min(dp[i][j], val1 + val2)
			k += -1
		j += 1
	i += -1
print(dp[0][n - 1])


n = int(input())
dp = [[None for j in range(n)] for i in range(n)]
cl = input().split(' ')
cl = [int(color) for color in cl]
for bias in range(0, n):
	for l in range(n - bias):
		r = l + bias
		loc = float('+inf')
		if bias == 0:
			dp[l][r] = 1
		elif bias == 1:
			if cl[l] == cl[r]:
				dp[l][r] = 1
			else:
				dp[l][r] = 2
		else:
			if cl[l] == cl[r]:
				loc = dp[l + 1][r - 1]
			for k in range(l, r):
				loc = min(loc, dp[l][k] + dp[k + 1][r])
			dp[l][r] = loc
print(dp[0][n - 1])


import os
import sys
from io import BytesIO, IOBase

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	dp = [[0] * (n + 1) for _ in range(n + 1)]
	for i in range(n):
		dp[i][i] = 1
	for dff in range(2, n + 1):
		for l in range(n - dff + 1):
			r = l + dff - 1
			if dff == 2:
				if arr[l] == arr[r]:
					dp[l][r] = 1
				else:
					dp[l][r] = 2
				continue
			m = 1000
			for i in range(l + 2, r + 1):
				if arr[l] == arr[i]:
					m = min(m, dp[l + 1][i - 1] + dp[i + 1][r])
			m = min(m, 1 + dp[l + 1][r])
			if arr[l] == arr[l + 1]:
				m = min(m, 1 + dp[l + 2][r])
			dp[l][r] = m
	print(dp[0][n - 1])
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
C = list(map(int, input().split()))
dp = [[0] * n for _ in range(n)]
for i in range(n):
	dp[i][i] = 1
for i in range(n - 2, -1, -1):
	for j in range(i + 1, n):
		dp[i][j] = 1 + dp[i + 1][j]
		if C[i] == C[i + 1]:
			dp[i][j] = min(dp[i][j], 1 + (dp[i + 2][j] if i + 2 < n else 0))
		for k in range(i + 2, j):
			if C[i] == C[k]:
				dp[i][j] = min(dp[i][j], dp[i + 1][k - 1] + dp[k + 1][j])
		if C[i] == C[j] and j - i > 1:
			dp[i][j] = min(dp[i][j], dp[i + 1][j - 1])
print(dp[0][n - 1])


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 30, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

def merge(arr, temp, left, mid, right):
	inv_count = 0
	i = left
	j = mid
	k = left
	while i <= mid - 1 and j <= right:
		if arr[i] <= arr[j]:
			temp[k] = arr[i]
			k += 1
			i += 1
		else:
			temp[k] = arr[j]
			k += 1
			j += 1
			inv_count = inv_count + (mid - i)
	while i <= mid - 1:
		temp[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp[k] = arr[j]
		k += 1
		j += 1
	for i in range(left, right + 1, 1):
		arr[i] = temp[i]
	return inv_count

def _mergeSort(arr, temp, left, right):
	inv_count = 0
	if right > left:
		mid = int((right + left) / 2)
		inv_count = _mergeSort(arr, temp, left, mid)
		inv_count += _mergeSort(arr, temp, mid + 1, right)
		inv_count += merge(arr, temp, left, mid + 1, right)
	return inv_count

def countSwaps(arr, n):
	temp = [0 for i in range(n)]
	return _mergeSort(arr, temp, 0, n - 1)

def minSwaps(arr):
	n = len(arr)
	arrpos = [*enumerate(arr)]
	arrpos.sort(key=lambda it: it[1])
	vis = {k: False for k in range(n)}
	ans = 0
	for i in range(n):
		if vis[i] or arrpos[i][0] == i:
			continue
		cycle_size = 0
		j = i
		while not vis[j]:
			vis[j] = True
			j = arrpos[j][0]
			cycle_size += 1
		if cycle_size > 0:
			ans += cycle_size - 1
	return ans

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
n = int(input())
l = list(map(int, input().split()))
dp = [[9999999999999 for i in range(n + 1)] for j in range(n + 1)]
for i in range(n + 1):
	dp[i][i] = 1
	for j in range(i):
		dp[i][j] = 0
for i in range(n):
	for j in range(i - 1, -1, -1):
		if j != i - 1 and l[j] == l[i]:
			dp[j][i] = min(dp[j][i], dp[j + 1][i - 1])
		if l[j] == l[j + 1]:
			dp[j][i] = min(1 + dp[j + 2][i], dp[j][i])
		dp[j][i] = min(dp[j][i], dp[j][i - 1] + 1, dp[j + 1][i] + 1)
		for k in range(j + 2, i):
			if l[j] == l[k]:
				dp[j][i] = min(dp[j][i], dp[j + 1][k - 1] + dp[k + 1][i])
print(dp[0][n - 1])


from math import inf
n = int(input())
s = [int(X) for X in input().split()]
dp = [[inf for i in range(n)] for j in range(n)]
isdp = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
	isdp[i][i] = 1
for i in range(1, n):
	for j in range(n):
		if i + j >= n:
			break
		if s[j] == s[i + j]:
			isdp[j][j + i] = isdp[j + 1][j + i - 1]
for i in range(n):
	dp[i][i] = 1
for i in range(n - 1, -1, -1):
	for j in range(1, n):
		if i + j >= n:
			break
		if isdp[i][j + i]:
			dp[i][i + j] = 1
			continue
		for p in range(i, i + j):
			dp[i][i + j] = min(dp[i][i + j], dp[p + 1][i + j] + dp[i][p])
		if s[i] == s[i + j]:
			if j == 1:
				dp[i][j + i] = 1
			else:
				dp[i][i + j] = min(dp[i + 1][j + i - 1], dp[i][j + i])
print(dp[0][n - 1])


dp = [[-1 for i in range(505)] for j in range(505)]
n = int(input())
A = [int(i) for i in input().split()]

def do(i, j):
	if i >= j:
		dp[i][j] = 1
		return 1
	if dp[i][j] != -1:
		return dp[i][j]
	ans = len(A)
	if A[i] == A[j]:
		ans = min(ans, do(i + 1, j - 1))
	for x in range(i, j):
		left = do(i, x)
		right = do(x + 1, j)
		ans = min(ans, left + right)
	dp[i][j] = ans
	return ans
if len(set(A)) == n:
	print(n)
else:
	print(do(0, n - 1))


n = int(input())
seg = n - 1
gemstones = [0] * 501
i = 0
for j in input().split(' '):
	gemstones[i] = int(j)
	i += 1
matriz = [[0] * 501 for i in range(501)]
for k in range(1, n + 1):
	ini = 0
	fim = k - 1
	while fim < n:
		if k == 1:
			matriz[ini][fim] = 1
		else:
			matriz[ini][fim] = matriz[ini + 1][fim] + 1
			if gemstones[ini] == gemstones[ini + 1]:
				matriz[ini][fim] = min(matriz[ini][fim], matriz[ini + 2][fim] + 1)
			for l in range(ini + 2, fim + 1):
				if gemstones[ini] == gemstones[l]:
					matriz[ini][fim] = min(matriz[ini][fim], matriz[ini + 1][l - 1] + matriz[l + 1][fim])
		ini += 1
		fim += 1
print(matriz[0][seg])


from sys import stdin, stdout
for _ in range(1):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	dp = [[0 for _ in range(n)] for _ in range(n)]
	for sz in range(n):
		for i in range(n - sz):
			j = i + sz
			if sz == 0:
				dp[i][j] = 1
			elif sz == 1:
				dp[i][j] = 1 + int(a[i] != a[j])
			else:
				v = n
				if a[i] == a[j]:
					v = dp[i + 1][j - 1]
				for k in range(i, j):
					v = min(v, dp[i][k] + dp[k + 1][j])
				dp[i][j] = v
	print(dp[0][n - 1])


import sys
input = sys.stdin.readline
n = int(input())
c = list(map(int, input().split()))
dp = [[-1] * (n + 1) for i in range(n + 1)]

def calc(l, r):
	if l > r:
		return 0
	elif l == r:
		return 1
	elif dp[l][r] != -1:
		return dp[l][r]
	res = 10 ** 9
	if c[l] == c[l + 1]:
		res = min(res, calc(l + 2, r) + 1)
	for k in range(l + 2, r + 1):
		if c[l] == c[k]:
			res = min(res, calc(l + 1, k - 1) + calc(k + 1, r))
	dp[l][r] = min(res, 1 + calc(l + 1, r))
	return dp[l][r]
print(calc(0, n - 1))


def main():
	(n, l) = (int(input()), list(map(int, input().split())))
	dp = [[0] * n for _ in range(n + 1)]
	for le in range(1, n + 1):
		for (lo, hi) in zip(list(range(n)), list(range(le - 1, n))):
			(row, c) = (dp[lo], l[lo])
			if le == 1:
				row[hi] = 1
			else:
				tmp = [1 + dp[lo + 1][hi]]
				if c == l[lo + 1]:
					tmp.append(1 + dp[lo + 2][hi])
				for match in range(lo + 2, hi + 1):
					if c == l[match]:
						tmp.append(dp[lo + 1][match - 1] + dp[match + 1][hi])
				row[hi] = min(tmp)
	print(dp[0][n - 1])

def __starting_point():
	main()
__starting_point()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	n = N()
	arr = RLL()
	dp = [[n] * n for _ in range(n)]
	for i in range(n):
		dp[i][i] = 1
	for le in range(2, n + 1):
		for l in range(n):
			r = l + le - 1
			if r >= n:
				break
			if le == 2:
				if arr[l] == arr[r]:
					dp[l][r] = 1
				else:
					dp[l][r] = 2
			else:
				for m in range(l, r):
					dp[l][r] = min(dp[l][r], dp[l][m] + dp[m + 1][r])
				if arr[l] == arr[r]:
					dp[l][r] = min(dp[l + 1][r - 1], dp[l][r])
	print(dp[0][-1])
main()


import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, A):
	dp = [[N for _ in range(N + 1)] for _ in range(N)]
	for i in range(N):
		dp[i][0] = 0
		dp[i][1] = 1
	for l in range(2, N + 1):
		for i in range(N - l + 1):
			for j in range(1, l):
				dp[i][l] = min(dp[i][l], dp[i][j] + dp[i + j][l - j])
			if i + 1 < N and A[i] == A[i + l - 1]:
				dp[i][l] = max(1, dp[i + 1][l - 2])
			else:
				dp[i][l] = min(dp[i][l], 1 + dp[i][l - 1])
				if i + 1 < N:
					dp[i][l] = min(dp[i][l], 1 + dp[i + 1][l - 1])
			for j in range(i + 1, i + l - 2):
				if A[i] == A[j]:
					dp[i][l] = min(dp[i][l], max(dp[i + 1][j - i - 1], 1) + max(dp[j + 1][i + l - j - 1], 1))
				if A[j] == A[i + l - 1]:
					dp[i][l] = min(dp[i][l], max(dp[i][j - i], 1) + max(dp[j + 1][i + l - j - 2], 1))
	return dp[0][N]
N = int(input())
A = [int(x) for x in input().split()]
print(solve(N, A))


n = int(input())
c = list(map(int, input().split()))
dp = [[float('inf') for i in range(n)] for j in range(n)]
size = n - 1
const = 0
var = 0
count = 0
for i in range(n):
	const = 0
	var = count
	while var <= size:
		if const == var:
			dp[const][var] = 1
		elif var - const == 1:
			dp[const][var] = 1 if c[const] == c[var] else 2
		else:
			if c[const] == c[var]:
				dp[const][var] = dp[const + 1][var - 1]
			add = const
			for j in range(var - const):
				dp[const][var] = min(dp[const][var], dp[const][add] + dp[add + 1][var])
				add += 1
		var += 1
		const += 1
	count += 1
print(dp[0][n - 1])


n = int(input())
t = tuple(map(int, input().split()))
m = [[1] * n for i in range(n + 1)]
for d in range(2, n + 1):
	for i in range(n - d + 1):
		m[d][i] = min((m[x][i] + m[d - x][i + x] for x in range(1, d)))
		if t[i] == t[i + d - 1]:
			m[d][i] = min(m[d][i], m[d - 2][i + 1])
print(m[n][0])


dp = []

def calculate(i, j, colors):
	if i > j:
		return 0
	if dp[i][j] == -1:
		if i == j:
			return 1
		dp[i][j] = 10000
		dp[i][j] = min(dp[i][j], 1 + calculate(i + 1, j, colors))
		if colors[i] == colors[i + 1]:
			dp[i][j] = min(dp[i][j], 1 + calculate(i + 2, j, colors))
		for k in range(i + 2, j + 1):
			if colors[k] == colors[i]:
				dp[i][j] = min(dp[i][j], calculate(i + 1, k - 1, colors) + calculate(k + 1, j, colors))
	return dp[i][j]

def solve():
	t = int(input())
	colors = list(map(int, input().split()))
	[dp.append([-1] * len(colors)) for x in range(len(colors))]
	print(calculate(0, len(colors) - 1, colors))
try:
	solve()
except Exception as e:
	print(e)


def main():
	(n, l) = (int(input()), list(map(int, input().split())))
	dp = [[0] * n for _ in range(n)]
	for i in range(n):
		dp[i][i] = 1
	for i in range(n - 1, 0, -1):
		(ci, row) = (l[i - 1], dp[i])
		for j in range(i, n):
			tmp = [1 + row[j]]
			if ci == l[i]:
				tmp.append(1 + dp[i + 1][j] if i + 1 < n else 1)
			for k in range(i + 1, j):
				if ci == l[k]:
					tmp.append(row[k - 1] + dp[k + 1][j])
			if ci == l[j] and j > i:
				tmp.append(row[j - 1])
			dp[i - 1][j] = min(tmp)
	print(dp[0][n - 1])

def __starting_point():
	main()
__starting_point()


n = int(input())
c = [*map(int, input().split())]
inf = n + 1
dp = [[inf for _ in range(n)] for __ in range(n)]

def find(l, r):
	if l > r:
		return 0
	if l == r or (l == r - 1 and c[l] == c[r]):
		dp[l][r] = 1
		return 1
	if dp[l][r] != inf:
		return dp[l][r]
	m = 1 + find(l + 1, r)
	for i in range(l + 2, r + 1):
		if c[l] == c[i]:
			m = min(m, find(l + 1, i - 1) + find(i + 1, r))
	if c[l] == c[l + 1]:
		m = min(m, find(l + 2, r) + 1)
	dp[l][r] = m
	return m
mi = inf
for i in range(n):
	mi = min(find(0, i) + find(i + 1, n - 1), mi)
print(mi)