Problem 949
Paint Fence
Medium · 20 pts · Dynamic Programming
Problem
Paint a fence of N posts using K colours so that no three consecutive posts have the same colour (two neighbours of the same colour are fine). Count the ways modulo 1000000007. Let same(i) count the ways where post i matches post i - 1 and diff(i) the ways where it differs: same(i) = diff(i - 1), and diff(i) = (same(i - 1) + diff(i - 1)) × (K - 1). Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).
Input
A single line with N and K.
Output
Print the number of ways modulo 1000000007.
Constraints
1 <= N <= 100000; 1 <= K <= 10^5
Example input
3 2
Example output
6
Explanation
With 3 posts and 2 colours there are 8 colourings, and only RRR and GGG put three equal colours in a row. So the answer is 6.