Number Sequence(hdu1005矩阵二分幂)

题意:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

Given A, B, and n, you are to calculate the value of f(n).

给你 A ,B,n 求出f(n)

思路:一看就是常系数线性齐次递推关系,矩阵二分幂

矩阵二分幂:http://blog.csdn.net/leonharetd/article/details/8956190

|  f[n]    |    =   |  a*f[n-1] + b*f[n-2] |   

| f[n-1] |         |           f[n-1]             |   

根据矩阵乘法得到  原式 = |  a  b  |   *  | f[n-1]  | 

                                              |  1   0 |       | f[n-2]  | 

同理:

|  f[n-1]    |    =   | a  b  |   *  | f[n-21  | 

|  f[n-2]    |     |  1   0 |       | f[n-2]  |



|    f[n]    |  =  |  a   b   |  ^ n-1  *  |   f[1]    |

|  f[n-1]  |      |   1   0 |      |    f[0]   |

问题就转化为了求

|   a   b |   的n - 1次方可以用矩阵二分幂

|   1   0 |  

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

struct Matrix
{
    int row[2][2];
};
Matrix num,ans,r;
int a,b,n;
void init()
{
    num.row[0][0] = 0,num.row[0][1] = b;
    num.row[1][0] = 1,num.row[1][1] = a;

    r.row[0][0] = 1,r.row[0][1] = 1;
    r.row[1][0] = 1,r.row[1][1] = (a+b) % 7;
}
Matrix Matrix_Mul(Matrix a,Matrix b)
{
    Matrix sum;
    int i,j;
    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
        {
            sum.row[i][j] = ( (a.row[i][0]*b.row[0][j])%7 + (a.row[i][1]*b.row[1][j] )% 7 ) % 7;
        }
    }
    return sum;
}

void getdata(int m)
{
    ans = num;
    while(m)
    {
        if(m&1)
            r = Matrix_Mul(r,ans);
        ans = Matrix_Mul(ans,ans);
        m = m >> 1;
    }
}
int main()
{
    while(scanf("%d%d%d",&a,&b,&n) != EOF)
    {
        if(a == 0 && b == 0  && n == 0 )
                break;
        init();
        getdata(--n);
        printf("%d\n",r.row[0][0]);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值