Hdu 1757 A Simple Math Problem

A Simple Math Problem

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


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
2007省赛集训队练习赛(6)_linle专场
 

Recommend
lcy


解法:n阶常系数线性递推方程矩阵解法


#include<stdio.h>
#include<string.h>

#define MAXN 11

__int64 map[MAXN][MAXN],tmp1[MAXN][MAXN],tmp2[MAXN][MAXN];

void fun(__int64 a,__int64 m)       //矩阵的快速幂
{
    int i,j,k;
    a--;
    for(i=1;i<=10;i++)
        for(j=1;j<=10;j++)
            tmp1[i][j]=map[i][j];
    while(a)
    {
        if(a%2)
        {
            for(i=1;i<=10;i++)
                for(j=1;j<=10;j++)
                    tmp2[i][j]=map[i][j];
            for(i=1;i<=10;i++)
                for(j=1;j<=10;j++)
                {
                    map[i][j]=0;
                    for(k=1;k<=10;k++)
                        map[i][j]=(map[i][j]+(tmp1[i][k]*tmp2[k][j]))%m;
                }
        }
        a/=2;
        for(i=1;i<=10;i++)
            for(j=1;j<=10;j++)
                tmp2[i][j]=tmp1[i][j];
        for(i=1;i<=10;i++)
            for(j=1;j<=10;j++)
            {
                tmp1[i][j]=0;
                for(k=1;k<=10;k++)
                    tmp1[i][j]=(tmp1[i][j]+tmp2[i][k]*tmp2[k][j])%m;
            }
    }
}

int main(void)
{
    __int64 k,m,i,j;
//    freopen("d:\\in.txt","r",stdin);
    while(scanf("%I64d%I64d",&k,&m)==2)
    {
        if(k<10)
            printf("%I64d",k%m);
        else
        {
            memset(map,0,sizeof(map));
            for(i=1;i<=10;i++)
                scanf("%I64d",&map[1][i]);
            for(i=2;i<=10;i++)
                map[i][i-1]=1;
            fun(k-9,m);
            __int64 s=0;
            for(i=1;i<=10;i++)
                s=(s+map[1][i]*(10-i))%m;
            printf("%I64d\n",s);
        }
    }
    return 0;
}


你可能感兴趣的:(Math,function,input,each,fun,output)