*HDU 1757 矩阵乘法

Posted LuZhiyuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了*HDU 1757 矩阵乘法相关的知识,希望对你有一定的参考价值。

A Simple Math Problem

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4307    Accepted Submission(s): 2586


Problem Description
Lele now is thinking about a simple function f(x).

If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .

Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.
 

 

Input
The problem contains mutiple test cases.Please process to the end of file.
In each case, there will be two lines.
In the first line , there are two positive integers k and m. ( k<2*10^9 , m < 10^5 )
In the second line , there are ten integers represent a0 ~ a9.
 

 

Output
For each case, output f(k) % m in one line.
 

 

Sample Input
10 9999
1 1 1 1 1 1 1 1 1 1
20 500
1 0 1 0 1 0 1 0 1 0
 

 

Sample Output
45
104
 

 

Author
linle
 

 

Source
 
题意:
If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .
上面的递推式计算f(k)。计算结果%m;
代码:
 1 //普通递推会超时,用矩阵乘法。
 2 #include<bits\stdc++.h>
 3 using namespace std;
 4 int a[12],f[12]={9,8,7,6,5,4,3,2,1,0};
 5 int k,m;
 6 struct Lu
 7 {
 8     int mp[12][12];
 9 }L1;
10 void init()
11 {
12     memset(L1.mp,0,sizeof(L1.mp));
13     for(int i=1;i<=9;i++)
14     {
15         L1.mp[i][i-1]=1;
16     }
17     for(int i=0;i<=9;i++)
18     {
19         L1.mp[0][i]=a[i];
20     }
21 }
22 Lu mult(Lu a,Lu b)
23 {
24     Lu c;
25     for(int i=0;i<=9;i++)
26     for(int j=0;j<=9;j++)
27     {
28         c.mp[i][j]=0;
29         for(int k=0;k<=9;k++)
30         c.mp[i][j]+=(a.mp[i][k]*b.mp[k][j])%m;
31         c.mp[i][j]%=m;
32     }
33     return c;
34 }
35 Lu solve(int x)
36 {
37     if(x==1)
38     return L1;
39     if(x&1)
40     {
41         Lu q=solve(x-1);
42         return mult(q,L1);
43     }
44     else
45     {
46         Lu q=solve(x/2);
47         return mult(q,q);
48     }
49 }
50 int main()
51 {
52     while(scanf("%d%d",&k,&m)!=EOF)
53     {
54         for(int i=0;i<=9;i++)
55         scanf("%d",&a[i]);
56         if(k<10)
57         {
58             printf("%d\n",k%m);
59             continue;
60         }
61         init();
62         Lu tem=solve(k-9);
63         int ans=0;
64         for(int i=0;i<=9;i++)
65         ans+=(tem.mp[0][i]*f[i])%m;
66         printf("%d\n",ans%m);
67     }
68     return 0;
69 }

 

以上是关于*HDU 1757 矩阵乘法的主要内容,如果未能解决你的问题,请参考以下文章

矩阵快速幂(HDU-1757&&HDU-2604)

HDU 1757 矩阵相乘,快速幂模板题

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

hdu-1757 A Simple Math Problem---矩阵快速幂模板题

hdu 1757 A Simple Math Problem 矩阵快速幂

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