51nod 1113 矩阵快速幂

题目链接:51nod 1113 矩阵快速幂

模板题,学习下。

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 typedef long long ll;
 7 const int N = 101;
 8 const int mod = 1e9+7;
 9 int n, m;
10 struct Mat{//矩阵
11     ll mat[N][N];
12 };
13 Mat operator * (Mat a, Mat b){//一次矩阵乘法
14     Mat c;
15     memset(c.mat, 0, sizeof(c.mat));
16     int i, j, k;
17     for(k = 1; k <= n; ++k){
18         for(i = 1; i <= n; ++i){
19             if(a.mat[i][k] <= 0) continue;
20             for(j = 1; j <= n; ++j){
21                 if(b.mat[k][j] <= 0) continue;
22                 c.mat[i][j] += a.mat[i][k] * b.mat[k][j];
23                 c.mat[i][j] %= mod;
24             }
25         }
26     }
27     return c;
28 }
29 Mat operator ^ (Mat a, int k){//矩阵快速幂,a^k
30     Mat c;
31     int i, j;
32     for(i = 1; i <= n; ++i)
33         for(j = 1; j <= n; ++j)
34             c.mat[i][j] = (i == j);//初始化为单位矩阵
35     while(k){
36         if(k & 1)
37             c = c * a;
38         a = a * a;
39         k >>= 1;
40     }
41     return c;
42 }
43 int main(){
44     scanf("%d%d", &n, &m);
45     int i, j;
46     Mat a;
47     for(i = 1; i <= n; ++i)
48         for(j = 1; j <= n; ++j)
49             scanf("%lld", &a.mat[i][j]);
50     Mat c = a ^ m;
51     for(i = 1; i <= n; ++i){
52         for(j = 1; j < n; ++j)
53             printf("%lld ", c.mat[i][j]);
54         printf("%lld\n", c.mat[i][n]);
55     }
56     return 0;
57 }
View Code

 

posted @ 2016-10-26 19:30  GraceSkyer  阅读(288)  评论(0编辑  收藏  举报

~~~~~~ACM大牛语录,激励一下~~~~~~

为了世界的和平,为了女生的安全,我拼命做题,做题,做题!

用最短的时间,刷最多的题!

给我一滴泪,我就看到了你全部的海洋!

seize the hour, seize the day.

人生难免有无奈,幸福走远了,或是感叹幸福来迟了.其实我一直相信,无论手中的幸福是多么微不足道的感觉,我会把握住那每一分,每一秒,当幸福依旧像那百鸟般飞逝,终究无法掌握时,我会感谢它,曾经降临过!

A自己的题,让别人郁闷去吧

WA肠中过,AC心中留 TLE耳边过,AC特别牛

天然的悲苦和伤逝,过去有过,以后还会有

^*^一步一步往上爬^*^

AC就像练级,比赛就像PK. 练级不如PK好玩

其实,世上本没有ACM,AC的人多了,也便有了!

AC无止尽~ Seek you forever~

找呀找呀找水题,找到一个AC一个呀!

AC是检验程序的唯一标准。

真的猛士,敢于直面惨淡的人生,敢于正视淋漓的鲜血……