码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1757 A Simple Math Problem (矩阵快速幂)

时间:2016-06-03 22:41:25      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1757

在吴神的帮助下才明白如何构造矩阵,还是好弱啊。

此处盗一张图

技术分享

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8 
 9 typedef long long ll;
10 
11 const int N = 10;
12 
13 ll k,m;
14 int a[10];
15 
16 struct matrix
17 {
18     ll mat[N][N];
19 };
20 matrix base;
21 void initial()
22 {
23     memset(base.mat,0,sizeof(base.mat));
24     for(int i=0; i<N; i++)
25         base.mat[0][i]=a[i];
26     for(int i=1; i<N; i++)
27         for(int j=0; j<N; j++)
28             if(i==j+1)
29                 base.mat[i][j]=1;
30 }
31 matrix multi(matrix a,matrix b)
32 {
33     matrix tmp;
34     memset(tmp.mat,0,sizeof(tmp.mat));
35     for(int i=0; i<N; i++)
36         for(int j=0; j<N; j++)
37         {
38             for(int k=0; k<N; k++)
39                 tmp.mat[i][j]=tmp.mat[i][j]+a.mat[i][k]*b.mat[k][j]%m;
40             tmp.mat[i][j]%=m;
41         }
42     return tmp;
43 }
44 
45 ll cal(ll n)
46 {
47     matrix ans;
48     memset(ans.mat,0,sizeof(ans.mat));
49     for(int i=0; i<N; i++)
50         for(int j=0; j<N; j++)
51             if(i==j)
52                 ans.mat[i][j]=1;
53     while(n)
54     {
55         if(n&1)
56             ans=multi(base,ans);
57         base=multi(base,base);
58         n>>=1;
59     }
60 
61     ll sum=0;
62     for(int i=0; i<N; i++)
63         sum+=ans.mat[0][i]*(N-i-1)%m;
64     return sum%m;
65 }
66 int main()
67 {
68     while(~scanf("%lld%lld",&k,&m))
69     {
70         for(int i=0; i<N; i++)
71             scanf("%d",&a[i]);
72         if(k<10)
73             printf("%lld\n",k%m);
74         else
75         {
76             initial();
77             printf("%lld\n",cal(k-9));
78         }
79     }
80     return 0;
81 }

 

HDU 1757 A Simple Math Problem (矩阵快速幂)

标签:

原文地址:http://www.cnblogs.com/ExcuseMe/p/5557624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!