A Simple Math Problem (Fast Power of Matrix)

Topic link: http://acm.hdu.edu.cn/showproblem.php?pid=1757

Idea: Matrix fast power template problem, but because I just started matrix fast power, I often store the array f in reverse, which leads to a local error overnight, and almost explodes my mind...

The code is implemented as follows:

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 int k, m;
 5 int a[10], f[10], mp[10][10];
 6 
 7 void mulself(int a[10][10]) {
 8     int c[10][10];
 9     memset(c, 0, sizeof(c));
10     for(int i = 0; i < 10; i++) {
11         for(int j = 0; j < 10; j++) {
12             for(int k = 0; k < 10; k++) {
13                 c[i][j] = (c[i][j] + (long long)a[i][k] * a[k][j]) % m;
14             }
15         }
16     }
17     memcpy(a, c, sizeof(c));
18 }
19 
20 void mul(int f[10], int a[10][10]) {
21     int c[10];
22     memset(c, 0, sizeof(c));
23     for(int i = 0; i < 10; i++) {
24         for(int j = 0; j < 10; j++) {
25             c[i] = (c[i] + (long long)f[j] * a[j][i] ) % m;
26         }
27     }
28     memcpy(f, c, sizeof(c));
29 }
30 
31 int main() {
32     while(~scanf("%d%d", &k, &m)) {
33         for(int i = 0; i < 10; i++) {
34             scanf("%d", &a[i]);
35         }
36         for(int i = 0; i < 10; i++) {
37             f[i] = 9 - i;
38         }
39         if(k <10) {
40             printf("%d\n", f[k]);
41             continue;
42         }
43         memset(mp, 0, sizeof(mp));
44         for(int i = 0; i < 10; i++) {
45             mp[i][0] = a[i];
46         }
47         for(int i = 0; i < 9; i++) {
48             mp[i][i + 1] = 1;
49         }
50         k = k - 9;
51         for(; k; k >>= 1) {
52             if(k & 1) mul(f, mp);
53             mulself(mp);
54         }
55         printf("%d\n", f[0]);
56     }
57     return 0;
58 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324978614&siteId=291194637