*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;
代码:
 //普通递推会超时,用矩阵乘法。构造矩阵时右上角的(n-1)*(n-1)矩阵置为单位矩阵,第n行从 右 到 左 填入系数,快速幂之后第n行作为行矩阵乘递推式从 小 到 大 排列的列矩阵得到结果
//或者构造左下角的单位矩阵,第一行从 左 到 右 填入系数,快速幂之后第1行作为行矩阵乘递推式从 大 到 小 排列的列矩阵得到结果
#include<bits\stdc++.h>
using namespace std;
int a[],f[]={,,,,,,,,,};
int k,m;
struct Lu
{
int mp[][];
}L1;
void init()
{
memset(L1.mp,,sizeof(L1.mp));
for(int i=;i<=;i++)
{
L1.mp[i][i+]=;
}
for(int i=;i<=;i++)
{
L1.mp[][i]=a[-i];
}
}
Lu mult(Lu a,Lu b)
{
Lu c;
for(int i=;i<=;i++)
for(int j=;j<=;j++)
{
c.mp[i][j]=;
for(int k=;k<=;k++)
c.mp[i][j]+=(a.mp[i][k]*b.mp[k][j])%m;
c.mp[i][j]%=m;
}
return c;
}
Lu solve(int x)
{
if(x==)
return L1;
if(x&)
{
Lu q=solve(x-);
return mult(q,L1);
}
else
{
Lu q=solve(x/);
return mult(q,q);
}
}
int main()
{
while(scanf("%d%d",&k,&m)!=EOF)
{
for(int i=;i<=;i++)
scanf("%d",&a[i]);
if(k<)
{
printf("%d\n",k%m);
continue;
}
init();
Lu tem=solve(k-);
int ans=;
for(int i=;i<=;i++)
ans+=(tem.mp[][i]*f[i])%m;
printf("%d\n",ans%m);
}
return ;
}
 //普通递推会超时,用矩阵乘法。
#include<bits\stdc++.h>
using namespace std;
int a[],f[]={,,,,,,,,,};
int k,m;
struct Lu
{
int mp[][];
}L1;
void init()
{
memset(L1.mp,,sizeof(L1.mp));
for(int i=;i<=;i++)
{
L1.mp[i][i-]=;
}
for(int i=;i<=;i++)
{
L1.mp[][i]=a[i];
}
}
Lu mult(Lu a,Lu b)
{
Lu c;
for(int i=;i<=;i++)
for(int j=;j<=;j++)
{
c.mp[i][j]=;
for(int k=;k<=;k++)
c.mp[i][j]+=(a.mp[i][k]*b.mp[k][j])%m;
c.mp[i][j]%=m;
}
return c;
}
Lu solve(int x)
{
if(x==)
return L1;
if(x&)
{
Lu q=solve(x-);
return mult(q,L1);
}
else
{
Lu q=solve(x/);
return mult(q,q);
}
}
int main()
{
while(scanf("%d%d",&k,&m)!=EOF)
{
for(int i=;i<=;i++)
scanf("%d",&a[i]);
if(k<)
{
printf("%d\n",k%m);
continue;
}
init();
Lu tem=solve(k-);
int ans=;
for(int i=;i<=;i++)
ans+=(tem.mp[][i]*f[i])%m;
printf("%d\n",ans%m);
}
return ;
}
上一篇:hdu 1757 矩阵快速幂 **


下一篇:hdu 1757 矩阵连乘