Advertisement
unknown_0711

Untitled

Dec 26th, 2022
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. import java.util.*;
  2. class Solution{
  3. public static int solve(int n, int k) {
  4. if(n == 1){
  5. return k;
  6. }
  7.  
  8. // Initializing the 'DP' array.
  9. int[] dp = new int[n + 1];
  10.  
  11. // Updating the initial states.
  12. dp[1] = k;
  13. dp[2] = mul(k, k);
  14.  
  15. // Looping over from 3 to 'N'.
  16. for (int i = 3; i <= n; i++) {
  17. // Updating the 'DP' state.
  18. dp[i] = mul((k - 1), add(dp[i - 1], dp[i - 2]));
  19. }
  20.  
  21. // Returning the result.
  22. return dp[n];
  23. }
  24.  
  25. // Driver function to get the modular addition.
  26. public static int add(int a, int b) {
  27. int mod = (int)1e9 + 7;
  28. return (int)(((long)(a % mod) + (b % mod)) % mod);
  29. }
  30.  
  31. // Driver function to get the modular multiplication.
  32. public static int mul(int a, int b) {
  33. int mod = (int)1e9 + 7;
  34. return (int)(((long)(a % mod) * (b % mod)) % mod);
  35. }
  36. }
  37. public class Main {
  38. public static void main(String args[]) {
  39. Scanner sc = new Scanner(System.in);
  40. int n = sc.nextInt();
  41. int k = sc.nextInt();
  42. System.out.print(Solution.solve(n,k));
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement