Avoid Prefix Palindromes

1

1 votes
Dynamic Programming, Algorithms, String, Medium, Introduction to Dynamic Programming 1
Problem

A special palindrome is a palindrome of size N which contains at most K distinct characters such that any prefix of size between 2 and N 1 is not a palindrome.

You need to count the number of special palindromes.

For example, abba is a special palindrome with N = 4 and K = 2 and ababa is not a special palindrome because aba is a palindrome and its a prefix of ababa.

If N = 3 and K = 3, possible special palindromes are aba, aca, bab, bcb, cac and cbc. So the answer will be 6.

Input format

A single line comprising two integers N and K

Output format

Print the answer to the modulo 109+9.

Input Constraints

1N105

1K105

 

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

If we take our alphabet set as {a,b}, the two possible palindromes are aba and bab.

Editor Image

?