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

hdu 1757 A Simple Math Problem 矩阵快速幂

时间:2015-04-07 23:20:44      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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

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.
题意描述:这题题意没什么说的吧,如那个公式所示,给出k和m,然后求f(k)%m。
算法分析:看到k这么大,肯定暴力是不行的,这里得运用到矩阵快速幂。
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<cmath>
 6 #include<algorithm>
 7 #define inf 0x7fffffff
 8 using namespace std;
 9 
10 int K,m;
11 struct matrix
12 {
13     int an[12][12];
14 }temp;
15 
16 matrix multiply(matrix a,matrix b)
17 {
18     matrix c;
19     memset(c.an,0,sizeof(c.an));
20     for (int i=1 ;i<=10 ;i++)
21     {
22         for (int j=1 ;j<=10 ;j++)
23         {
24             for (int k=1 ;k<=10 ;k++)
25             {
26                 c.an[i][j]=(c.an[i][j]+a.an[i][k] * b.an[k][j])%m;
27                 c.an[i][j] %= m;
28             }
29         }
30     }
31     return c;
32 }
33 
34 int calc(int u)
35 {
36     matrix x;
37     memset(x.an,0,sizeof(x.an));
38     for (int j=1 ;j<=10 ;j++) x.an[j][1]=10-j;
39     while (u)
40     {
41         if (u&1) x=multiply(temp,x);
42         u >>= 1;
43         temp=multiply(temp,temp);
44     }
45     int sum=0;
46     return x.an[1][1]%m;
47 }
48 
49 int main()
50 {
51     while (scanf("%d%d",&K,&m)!=EOF)
52     {
53         for (int i=1 ;i<=10 ;i++) scanf("%d",&temp.an[1][i]);
54         if (K<=9) {printf("%d\n",K);continue; }
55         for (int i=2 ;i<=10 ;i++)
56         {
57             for (int j=1 ;j<=10 ;j++)
58                 temp.an[i][j]= i==j+1 ? 1 : 0 ;
59         }
60         printf("%d\n",calc(K-9));
61     }
62     return 0;
63 }

 

hdu 1757 A Simple Math Problem 矩阵快速幂

标签:

原文地址:http://www.cnblogs.com/huangxf/p/4399891.html

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