九度OJ題目1081:遞推數列解題報告
阿新 • • 發佈:2019-02-09
題目分析1:
一個很顯然的想法是遞推計算這k+1個數對10000的模,實現如下:原始碼1(TLE)
- #include <stdio.h>
- #include <stdlib.h>
- #define MOD 10000
- int main()
- {
- int a0, a1, p, q, k;
- while(scanf("%d%d%d%d%d", &a0, &a1, &p, &q, &k) != EOF)
- {
- int *pa = (int *)malloc(sizeof(int)*(k+1));
- pa[0] = a0;
- pa[1] = a1;
- int i;
- for(i = 2; i <= k; i++) //時間複雜度為O(k)
- pa[i] = (p * pa[i-1] + q * pa[i-2])%MOD;
- printf("%d\n", pa[k]);
- free(pa);
- }
- //system("pause");
- return 0;
- }
- /**************************************************************
- Problem: 1081
- User: superlc320
- Language: C++
- Result: Time Limit Exceed
- ****************************************************************/
題目分析2:
很不幸,超時了。以上演算法的時間複雜度為O(k), 當k很大時,會TLE。再次分析題目,會發現遞推公式原始碼2
- #include <stdio.h>
- #include <stdlib.h>
- #define MOD 10000 //結果取MOD,避免高精度運算
- /*將矩陣p與矩陣q相乘,結果存入p矩陣*/
- void Matrix_mul(int p[2][2], int q[2][2])
- {
- int i, j, k;
- int t[2][2]={0};
- for(i = 0; i <= 1; i++)
- for(j = 0; j <= 1; j++)
- for(k = 0; k <= 1; k++)
- t[i][j] += p[i][k] * q[k][j];
- for(i = 0; i <= 1; i++)
- for(j = 0; j <= 1; j++)
- p[i][j] = t[i][j] % MOD;
- }
- /*計算p矩陣的n次方,結果存入p矩陣*/
- void Matrix_cal(int p[2][2], int n)
- {
- int i, j;
- int t[2][2];
- for(i = 0; i <= 1; i++)
- for(j = 0; j <= 1; j++)
- t[i][j] = p[i][j];
- if(n == 1)
- return;
- elseif(n & 1)
- {
- Matrix_cal(p, n-1);
- Matrix_mul(p, t);
- }
- else
- {
- Matrix_cal(p, n/2);
- Matrix_mul(p, p);
- }
- }
- int main()
- {
- int a0, a1, p, q, k;
- while(scanf("%d%d%d%d%d", &a0, &a1, &p, &q, &k) != EOF)
- {
- if(k == 0)
- printf("%d\n", a0);
- elseif(k == 1)
- printf("%d\n", a1);
- else
- {
- int matrix[2][2] = { {p%MOD, q%MOD}, {1, 0} };
- Matrix_cal(matrix, k-1);
- printf("%d\n", (a1 * matrix[0][0] + a0 * matrix[0][1]) % MOD);
- }
- }
- //system("pause");
- return 0;
- }
- /**************************************************************
- Problem: 1081
- User: superlc320
- Language: C++
- Result: Accepted
- Time:10 ms
- Memory:1020 kb
- ****************************************************************/
![](http://static.blog.csdn.net/images/save_snippets.png)