hdu1757——矩阵快速幂入门

来源:互联网 发布:投影机写码软件 编辑:程序博客网 时间:2024/06/05 22:27

hdu1757A Simple Math Problem:http://acm.hdu.edu.cn/showproblem.php?pid=1757

A Simple Math Problem

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


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
递推式都给出了,直接上模板就行了

#include <iostream>#include <cstdlib>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <set>#include <queue>using namespace std;typedef long long ll;ll mod,n;ll f[10];typedef struct Node{    ll a[10][10];    Node()    {        memset(a,0,sizeof(a));    }} node;node fun(node x,node y){    node ans;    for(int i = 0; i < 10; i++)        for(int j = 0; j < 10; j++)            for(int k = 0; k < 10; k++)                ans.a[i][j] += x.a[i][k] * y.a[k][j] % mod,                               ans.a[i][j] %= mod;    return ans;}ll quickpow(ll x,node ans){    node tem;    for(int i = 0; i < 10; i++)        tem.a[i][0] = f[i];    for(int i = 1; i < 10 ; i++)        tem.a[i-1][i] = 1;    while(x)    {        if(x&1)ans = fun(ans,tem);        x >>= 1;        tem = fun(tem,tem);    }    return ans.a[0][0] % mod;}int main(){//    freopen("in.txt","r",stdin);    while(~scanf("%lld%lld",&n,&mod))    {        node ans;        for(int i = 0; i < 10; i++)            ans.a[i][i] = 1;        for(int i = 0; i < 10; i++)        {            scanf("%lld",&f[i]);            ans.a[0][i] = 9 - i;        }        if(n <= 9)printf("%lld\n",n % mod);        else printf("%lld\n",quickpow(n-9,ans));    }    return 0;}


0 0
原创粉丝点击