您的位置:首页 > 其它

HDOJ 1757 A Simple Math Problem

2016-10-30 19:55 246 查看

A Simple Math Problem

[b]Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 4281    Accepted Submission(s): 2571
[/b]

[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
For each case, output f(k) % m in one line.
 

[align=left]Sample Input[/align]

10 9999
1 1 1 1 1 1 1 1 1 1
20 500
1 0 1 0 1 0 1 0 1 0

 

[align=left]Sample Output[/align]

45
104

 

[align=left]Author[/align]
linle
 

[align=left]矩阵快速幂,难点在于怎么构造矩阵,好难啊,毕竟线代刚刚及格的渣渣。[/align]
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int n=10,k;
int mod;
struct Matrix
{
int m[10][10];
}M;
Matrix Mult(Matrix a,Matrix b)  //矩阵乘法
{
Matrix ans;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
ans.m[i][j]=0;
for(int k=0;k<n;k++)
{
ans.m[i][j]+=a.m[i][k]*b.m[k][j];
ans.m[i][j]%=mod;
}
}
}
return ans;
}
Matrix quickpow(Matrix a,int b)     //矩阵快速幂
{
Matrix ans;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
ans.m[i][j]=1;
else
ans.m[i][j]=0;
}
}
while(b)
{
if(b&1)
ans=Mult(ans,a);
a=Mult(a,a);
b/=2;
}
return ans;
}
int main()
{
while(scanf("%d%d",&k,&mod)!=EOF)
{
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
M.m[i][j]=0;
}
for(int i=0;i<10;i++)
scanf("%d",&M.m[0][i]);
if(k<10)
{
printf("%d\n",k%mod);
continue;
}
for(int i=1;i<10;i++)
M.m[i][i-1]=1;

M=quickpow(M,k-9);
Matrix N;
for(int i=0;i<10;i++)
{
N.m[i][0]=10-i-1;
for(int j=1;j<10;j++)
N.m[i][j]=0;
}
M=Mult(M,N);
int ans=0;
printf("%d\n",M.m[0][0]);
}
return 0;
}


[align=left]
[/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  矩阵快速幂