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

来源:互联网 发布:iphone8必备软件推荐 编辑:程序博客网 时间:2024/06/03 22:41

A Simple Math Problem

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


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 99991 1 1 1 1 1 1 1 1 120 5001 0 1 0 1 0 1 0 1 0
 

Sample Output
45104
 


给出 f(n) 的关系:  

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);

构造矩阵  

 


然后 利用 矩阵快速幂:

#include <iostream>#include <stdio.h>#include <cmath>#include <algorithm>#include <cstring>typedef long long ll;using namespace std;const int MAXN=10;const int N=20;int num[10];int MOD;struct Matrix{ll arr[N][N];void init(){memset(arr,0,sizeof(arr));for(int i=1;i<MAXN;i++)arr[i][i-1]=1;        for(int i=0;i<MAXN;i++)            arr[0][i]=num[i];}void iinit()//单位矩阵{    memset(arr,0,sizeof(arr));    for(int i=0;i<MAXN;i++)            arr[i][i]=1;}}A;Matrix mul(Matrix X,Matrix Y)//{Matrix ans;for(int i=0;i<MAXN;i++)for(int j=0;j<MAXN;j++){ans.arr[i][j]=0;for(int k=0;k<MAXN;k++)ans.arr[i][j]+=X.arr[i][k]*Y.arr[k][j];ans.arr[i][j]%=MOD;}return ans;}Matrix Q_pow(Matrix B,int n)// ¾ØÕó¿ìËÙÃÝ{Matrix ans;ans.iinit();while(n){if(n&1)ans=mul(ans,B);n>>=1;B=mul(B,B);}return ans;}int main(){    Matrix ans;    int k;    while(~scanf("%d %d",&k,&MOD))    {        memset(num,0,sizeof(num));        for(int i=0;i<=9;i++)            scanf("%d",&num[i]);        ans.init();//初始化        int res=0;        if(k<10){            printf("%d\n",k);            continue;        }        ans=Q_pow(ans,k-9);        for(int i=0;i<=9;i++)            res+=(ans.arr[0][i]*(9-i));        printf("%d\n",res%MOD);    }    return 0;}



阅读全文
0 0