Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Solution{
- public static int solve(int n, int k) {
- if(n == 1){
- return k;
- }
- // Initializing the 'DP' array.
- int[] dp = new int[n + 1];
- // Updating the initial states.
- dp[1] = k;
- dp[2] = mul(k, k);
- // Looping over from 3 to 'N'.
- for (int i = 3; i <= n; i++) {
- // Updating the 'DP' state.
- dp[i] = mul((k - 1), add(dp[i - 1], dp[i - 2]));
- }
- // Returning the result.
- return dp[n];
- }
- // Driver function to get the modular addition.
- public static int add(int a, int b) {
- int mod = (int)1e9 + 7;
- return (int)(((long)(a % mod) + (b % mod)) % mod);
- }
- // Driver function to get the modular multiplication.
- public static int mul(int a, int b) {
- int mod = (int)1e9 + 7;
- return (int)(((long)(a % mod) * (b % mod)) % mod);
- }
- }
- public class Main {
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int k = sc.nextInt();
- System.out.print(Solution.solve(n,k));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement