矩阵快速幂

51nod1113题:矩阵快速幂

矩阵快速幂与普通的快速幂思想一模一样,就是把数换成了矩阵,写这道题的时候,脑子抽了,忘记了单位矩阵的定义,搞得一直a不了,一定要牢记单位矩阵。

单位矩阵:1  0  0  0

     0  1  0  0

     0  0  1  0

     0  0  0  1.

最后附上代码,没用结构体,更好理解(其实是不会用)。

 1 #include<iostream>//花了三天写出来,结果只是弄错了单位矩阵的概念,不然第一次的时候就搞定了 
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<algorithm>
 5 #include<cstring>
 6 using namespace std;
 7 typedef long long ll;
 8 const ll mod=1e9+7;
 9 ll c[150][150],m,s[150][150],a[150][150];
10 int n;
11 void chen(ll (*p)[150],ll (*q)[150])
12 {
13     ll zj[150][150];
14     memset(zj,0,sizeof(zj));
15     /*for(int i=0;i<n;i++)
16     {
17         for(int j=0;j<n;j++)
18         {
19             cout<<q[i][j];
20         }
21         cout<<endl;
22     }*/
23     int i,j,k;
24     for(i=0;i<n;i++)
25         for(j=0;j<n;j++)
26         {
27             for(k=0;k<n;k++)
28             {
29                 zj[i][j]+=(((p[i][k])%mod)*((q[k][j])%mod))%mod;
30                 zj[i][j]%=mod;
31             //    cout<<p[i*n+k]<<" "<<p[k*n+k]<<endl;
32             }
33         }
34     for(i=0;i<n;i++)
35     {
36         for(j=0;j<n;j++)
37         {
38             p[i][j]=zj[i][j];
39             //cout<<zj[i][j]<<" ";
40         }
41         //cout<<endl;
42     }
43 }
44 int main()
45 {
46     scanf("%d%lld",&n,&m);
47     int i,j;
48     for(i=0;i<n;i++)
49         for(j=0;j<n;j++)
50         {
51             cin>>c[i][j];
52             if(i==j)s[i][j]=1;
53             else s[i][j]=0;
54         }
55     while(m>0)
56     {
57         //cout<<0000000000<<endl;
58         if(m&1) chen(s,c);
59         chen(c,c);
60         m>>=1;
61     }
62     for(i=0;i<n;i++)
63     {
64         for(j=0;j<n;j++)
65         {
66             printf("%lld",s[i][j]);
67             if(j!=n-1) printf(" ");
68         }
69         printf("\n");
70     }
71     return 0;        
72 }

猜你喜欢

转载自www.cnblogs.com/01cainiao/p/8907167.html