51nod1113(矩阵快速幂模板)

题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1113

题意:中文题诶~

思路:矩阵快速幂模板

代码:

 1 #include <iostream>
 2 #define ll long long
 3 using namespace std;
 4 
 5 const int mod = 1e9+7;
 6 const int MAXN = 1e2+10;
 7 int n, m;
 8 
 9 typedef struct node{
10     ll x[MAXN][MAXN];
11 }matrix;
12 
13 matrix matrix_multi(matrix a, matrix b){
14     matrix c;
15     for(int i=0; i<n; i++){
16         for(int j=0; j<n; j++){
17             ll cnt=0;
18             for(int k=0; k<n; k++){
19                 cnt += a.x[i][k]*b.x[k][j];
20                 if(cnt >= mod) cnt %= mod;
21             }
22             c.x[i][j] = cnt;
23         }
24     }
25     return c;
26 }
27 
28 matrix get_pow(matrix tmp, int m){
29     matrix ans;
30     for(int i=0; i<n; i++){
31         for(int j=0; j<n; j++){
32             if(i==j) ans.x[i][j] = 1;
33         }
34     }
35     while(m){
36         if(m&1) ans = matrix_multi(ans, tmp);
37         tmp = matrix_multi(tmp, tmp);
38         m >>= 1;
39     }
40     return ans;
41 }
42 
43 int main(void){
44     matrix cnt;
45     cin >> n >> m;
46     for(int i=0; i<n; i++){
47         for(int j=0; j<n; j++){
48             cin >> cnt.x[i][j];
49         }
50     }
51     matrix tmp = get_pow(cnt, m);
52     for(int i=0; i<n; i++){
53         for(int j=0; j<n; j++){
54             cout << tmp.x[i][j] << " ";
55         }
56         cout << endl;
57     }
58     return 0;
59 }
View Code
原文地址:https://www.cnblogs.com/geloutingyu/p/6863808.html