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

来源:互联网 发布:cst2014仿真软件下载 编辑:程序博客网 时间:2024/06/05 01:09

A Simple Math Problem
Time Limit: 1000MS
Memory Limit: 32768KB
64bit IO Format: %I64d & %I64u

SubmitStatus

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(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10),ai(0<=i<=9)为0或1

思路:可以用递推做,不过太耗时了,准TLE。用转化为矩阵,再用快速幂,复杂度大大的减少。

盗用一张图:


把问题转化为求矩阵的n-9次幂就行了;


<span style="font-size:18px;">#include <cstdio>#include <iostream>#include <cstring>#include <cmath>#include <string>#include <algorithm>#include <queue>#include <stack>using namespace std;const double PI = acos(-1.0);const double e = 2.718281828459;const double eps = 1e-8;int m, k;struct Matrix{    int m[10][10];    void clear()    {        memset(m, 0, sizeof(m));    }};Matrix multi(Matrix a, Matrix b){   //矩阵乘法    Matrix t;    t.clear();    for(int i = 0; i < 10; i++)    {        for(int j = 0; j < 10; j++)        {            for(int k = 0; k < 10; k++)            {                t.m[i][j] += a.m[i][k]*b.m[k][j];            }            t.m[i][j] %= m;        }    }    return t;}Matrix pow_mod(Matrix a, Matrix b){   //快速幂(反复平发法)    while(k)    {        if(k&1)            b = multi(a, b);        a = multi(a, a);        k >>= 1;    }    return b;}int main(){    //freopen("in.txt", "r", stdin);    //freopen("out.txt", "w", stdout);    while(cin>>k>>m)    {        Matrix a, b;        a.clear();        b.clear(); //构造矩阵a        for(int i = 1; i < 10; i++)        {            a.m[i][i-1] = 1;        }        //b为单元矩阵,相当于整数的1        for(int i = 0; i < 10; i++)        {            b.m[i][i] = 1;        }        for(int i = 0; i < 10; i++)        {            scanf("%d", &a.m[0][i]);        }        if(k < 10)        {            printf("%d\n", k%m);            continue;        }        k -= 9;        b = pow_mod(a, b); //求a的 n-9 次幂并保存在 b 中        int ans = 0;        for(int i = 0; i < 10; i++)            ans = (ans+b.m[0][i]*(9-i))%m; //最后乘上f[9],f[8],f[7]...f[0]        cout<<ans<<endl;    }    return 0;}</span>


0 0
原创粉丝点击