矩阵快速幂

本文介绍使用矩阵快速幂解决特定递推数列问题的方法,包括递推式定义、矩阵运算实现及模运算处理,通过具体示例展示了算法流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求递推式,构造一个矩阵,根据矩阵乘法规则,得到
f(n)=a1*f(n-1)+a2*f(n-2)+…+am*f(n-m)的第N项。

直接丢水题


A Simple Math Problem
HDU1757

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


题意:
第0项到第9项都是自己,后面的都是满足递推式的f(n),求第n项模m.


#include <iostream>
#include <stdio.h>
#include<string.h>
using namespace std;
int k, m;
struct matrix
{
    int  g[15][15];
    int n;
    matrix operator=(const matrix &b)
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                g[i][j] = b.g[i][j];
            }
        }
        return *this;
    }
};
matrix operator*(const matrix &a, const matrix &b)
{
    matrix c;
    int sum;
    for (int i = 0; i < a.n; i++)
    {
        for (int j = 0; j < a.n; j++)
        {
            int I;
            sum = 0;
            for (I = 0; I < a.n; I++)
            {
                sum = sum%m + (a.g[i][I] * b.g[I][j] % m);
                sum %= m;
            }
            c.g[i][j] = sum;
        }
    }
    return c;
}
matrix pow(matrix a, int b)
{
    matrix ans, base = a;
    ans.n = 10;
    for (int i = 0; i < ans.n; i++)
    {
        for (int j = 0; j < ans.n; j++)
        {
            if (i == j)
                ans.g[i][j] = 1;
            else ans.g[i][j] = 0;
        }
    }
    while (b)
    {
        if (b & 1)
        {
            ans = ans * base;
        }
        base = base * base;
        b >>= 1;
    }
    return ans;
}
int main()
{
    while (~scanf("%d%d", &k, &m))
    {
        matrix a, b;
        a.n = 10;
        b.n = 10;
        memset(a.g, 0, sizeof(a.g));
        memset(b.g, 0, sizeof(b.g));
        for (int i = 0; i < 10; i++)
        {
            scanf("%d", &b.g[i][0]);
            b.g[i][i + 1] = 1;
            a.g[0][i] = 9 - i;
        }
        if (k < 10)
        {
            cout << k << endl; continue;
        }
        k -= 9;
        b = pow(b, k);
        a = a*b;
        cout << a.g[0][0] << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值