51nod 1126 求递推序列的第N项(斐波那契)

基准时间限制:1 秒 空间限制:131072 KB 分值: 10  难度:2级算法题
 收藏
 关注
有一个序列是这样定义的:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
给出A,B和N,求f(n)的值。
Input
输入3个数:A,B,N。数字之间用空格分割。(-10000 <= A, B <= 10000, 1 <= N <= 10^9)
Output
输出f(n)的值。
Input示例
3 -1 5
Output示例
6
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int mod=7;
struct mx
{
    LL a[2][2];
};
mx solve(mx a,mx b)
{
    mx c;
    for(int i=0; i<2; i++)
        for(int j=0; j<2; j++)
        {
            c.a[i][j]=0;
            for(int k=0; k<2; k++)
            {
                c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;
            }

        }
    return c;
}
mx qpow(mx t,LL n)
{
    mx ans;
    ans.a[0][0]=ans.a[1][1]=1;
    ans.a[0][1]=ans.a[1][0]=0;
    while(n)
    {
        if(n&1)
            ans=solve(ans,t);
        n>>=1;
        t=solve(t,t);
    }
    return ans;
}
int main()
{
    LL a,b,n;
    scanf("%lld%lld%lld",&a,&b,&n);
    if(n==1||n==2)
        printf("1\n");
    else
    {
        mx t={(a%7+7)%7,(b%7+7)%7,1,0};
        mx ans=qpow(t,n-2);
        t={1,0,1,0};   //t={f[2],0,f[1],0}!!!!!
        ans=solve(ans,t);
        printf("%lld\n",ans.a[0][0]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值