题目链接:https://www.dotcpp.com/oj/problem1907.html

    题目分析:

    • 本来以为直接for循环模拟可以过的,但是显示超时了
    • 将快速幂算法扩展为矩阵快速幂,然后求解。

    image.png
    :但是这个在C语言网上显示运行错误,尚不清楚错哪,逻辑和在本地上运行是正确的。

    1. import java.util.*;
    2. public class Main{
    3. public static long mod = 99999999;
    4. public static long[][] fact(long[][] mat, int n){
    5. if (n == 1){
    6. return mat;
    7. }
    8. long[][] pow = new long[mat.length][mat.length];
    9. for(int i = 0; i < mat.length; i++){
    10. for (int j = 0; j < mat.length; j++){
    11. pow[i][j] = mat[i][j];
    12. }
    13. }
    14. while(n != 0){
    15. if((n & 1) == 1){
    16. long[][] var = new long[mat.length][mat.length];
    17. for(int i = 0; i < mat.length; i++){
    18. for (int j = 0; j < mat.length; j++){
    19. for (int k = 0; k < mat.length; k++){
    20. var[i][j] = (var[i][j] + (mat[i][k] * pow[k][j]) % mod) % mod;
    21. }
    22. }
    23. }
    24. for(int i = 0; i < mat.length; i++){
    25. for (int j = 0; j < mat.length; j++){
    26. mat[i][j] = var[i][j];
    27. }
    28. }
    29. }else{
    30. long[][] var = new long[mat.length][mat.length];
    31. for(int i = 0; i < mat.length; i++){
    32. for (int j = 0; j < mat.length; j++){
    33. for (int k = 0; k < mat.length; k++){
    34. var[i][j] = (var[i][j] + (pow[i][k] * pow[k][j]) % mod) % mod;
    35. }
    36. }
    37. }
    38. for(int i = 0; i < mat.length; i++){
    39. for (int j = 0; j < mat.length; j++){
    40. pow[i][j] = var[i][j];
    41. }
    42. }
    43. }
    44. n >>= 1;
    45. }
    46. return mat;
    47. }
    48. public static void main(String[] args) {
    49. Scanner sc = new Scanner(System.in);
    50. int n = sc.nextInt();
    51. if(n == 1){
    52. System.out.println(2);
    53. System.out.println(3);
    54. }else if(n == 2){
    55. System.out.println(1);
    56. System.out.println(4);
    57. }else if(n == 3){
    58. System.out.println(6);
    59. System.out.println(5);
    60. }else{
    61. long[] v = {6, 5, 1, 4, 2, 3, 1};
    62. long[][] mat = {{0, 1, 1, 0, 0, 0, 0},
    63. {1, 0, 0, 1, 0, 0, 0},
    64. {0, 0, 0, 0, 1, 0, 0},
    65. {0, 0, 0, 0, 0, 1, 0},
    66. {2, 3, 0, 0, 0, 0, 0},
    67. {0, 2, 0, 0, 0, 0, 0},
    68. {5, 3, 0, 0, 0, 0, 1}};
    69. long[][] mat2 = fact(mat, n - 3);
    70. long[] ans = new long[2];
    71. for(int k = 0; k < 2; k++){
    72. long temp = 0;
    73. for(int i = 0; i < v.length; i++){
    74. temp = (temp + (v[i] * mat[i][k]) % mod) % mod;
    75. }
    76. ans[k] = temp;
    77. }
    78. System.out.println(ans[0]);
    79. System.out.println(ans[1]);
    80. }
    81. }
    82. }