
Input: 'N' = 3, 'K' = 2
Output: 6
Say we have the colors with the numbers 1 and 0. We can paint the fence with 3 posts with the following different combinations.
110
001
101
100
010
011
The first line of input contains an integer 'T', denoting the number of test cases.
Each test case will contain two integers 'N' and 'K' denoting the number of posts on the fence and the number of colors Ninja has.
For each test case, print the number of ways modulo 10^9 + 7 to paint the fence.
Output for each test case will be printed in a separate line.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 10
1 <= 'N' <= 10^5
1 <= 'K' <= 10^5
Time Limit: 1 sec
Assume that both 'solve(n - 1)' and 'solve(n - 2)' are valid results, which means the last 2nd color is mush not equivalent to the last 3rd color. And then, the previous three colors have (k - 1) different choices.
Then the formula will be
solve(n) = solve(n - 1) * (k - 1) - solve(n - 2) * (k - 1)
We will use the above formula to find the answer recursively.
Algorithm :
Define the function 'add', which will return the modulo addition of two numbers.
Define the function 'mul', which will return modulo multiplication of two numbers.
// Function to get the number of ways to paint the fence with 'N' posts with 'K' colors available.
solve(N, K):
numberOfWays(N, K)
Algorithm :
Define the function 'add', which will return the modulo addition of two numbers.
Define the function 'mul', which will return modulo multiplication of two numbers.
// Function to get the number of ways to paint the fence with 'N' posts with 'K' colors available.
solve(N, K, DP):
numberOfWays(N, K)
Algorithm :
Define the function 'add', which will return the modulo addition of two numbers.
Define the function 'mul', which will return modulo multiplication of two numbers.
numberOfWays(N, K)
As we can see, we only require the last two-step results for each step. Hence we can store them only and use them later.
Algorithm :
Define the function 'add', which will return the modulo addition of two numbers.
Define the function 'mul', which will return modulo multiplication of two numbers.
numberOfWays(N, K)