UVa 10870 (矩阵快速幂) Recurrences

给出一个d阶线性递推关系,求f(n) mod m的值。

UVa 10870 (矩阵快速幂) Recurrences,

 求出An-dv0,该向量的最后一个元素就是所求。

 1 #include <iostream>

 2 #include <cstdio>

 3 #include <cstring>

 4 using namespace std;

 5 

 6 const int maxn = 20;

 7 

 8 typedef long long Matrix[maxn][maxn];

 9 typedef long long Vector[maxn];

10 

11 int d, n, m;

12 

13 void matrix_mul(Matrix A, Matrix B, Matrix res)

14 {

15     Matrix C;

16     memset(C, 0, sizeof(C));

17     for(int i = 0; i < d; i++)

18         for(int j = 0; j < d; j++)

19             for(int k = 0; k < d; k++)

20                 C[i][j] = (C[i][j] + A[i][k]*B[k][j]) % m;

21     memcpy(res, C, sizeof(C));

22 }

23 

24 void matrix_pow(Matrix A, int n, Matrix res)

25 {

26     Matrix a, r;

27     memcpy(a, A, sizeof(a));

28     memset(r, 0, sizeof(r));

29     for(int i = 0; i < d; i++) r[i][i] = 1;

30     while(n)

31     {

32         if(n&1) matrix_mul(r, a, r);

33         n >>= 1;

34         matrix_mul(a, a, a);

35     }

36     memcpy(res, r, sizeof(r));

37 }

38 

39 int main()

40 {

41     //freopen("in.txt", "r", stdin);

42 

43     while(cin >> d >> n >> m && d)

44     {

45         Matrix A;

46         memset(A, 0, sizeof(A));

47         Vector a, f;

48         for(int i = 0; i < d; i++) { cin >> a[i]; a[i] %= m; }

49         for(int i = 0; i < d; i++) { cin >> f[i]; f[i] %= m; }

50         if(n <= d) { cout << f[n-1] << "\n"; continue; }

51         for(int i = 0; i < d-1; i++) A[i][i+1] = 1;

52         for(int i = 0; i < d; i++) A[d-1][i] = a[d-i-1];

53         matrix_pow(A, n-d, A);

54         long long ans = 0;

55         for(int i = 0; i < d; i++) ans = (ans + A[d-1][i]*f[i]) % m;

56         cout << ans << "\n";

57     }

58 

59     return 0;

60 }
代码君

 

你可能感兴趣的:(uva)