Jzzhu and Sequences CodeForces - 450B

本文介绍了一种利用矩阵快速幂优化递归计算的方法,通过具体实例演示了如何求解特定序列的第n项,模10^9+7的结果。此方法适用于类似斐波那契数列的问题。

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

题目描述

Jzzhu has invented a kind of sequences, they meet the following property:

You are given x and y, please calculate fn modulo 1000000007 (109 + 7).

输入

The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).

输出

Output a single integer representing fn modulo 1000000007 (109 + 7).

样例输入

2 3
3

样例输出

1

样例输入

0 -1
2

样例输出

1000000006

提示

In the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.

In the second sample, f2 =  - 1;  - 1 modulo (109 + 7) equals (109 + 6).


题意

题目给出递推关系。
类似于求斐波那契数列。

思路

用矩阵快速幂优化递推时间。
注意mod
关系。负数要%mod 再+mod 再%mod。

代码

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <string>
#define mem(a) memset(a,0,sizeof(a))
#define mem2(a) memset(a,-1,sizeof(a))
#define mod 1000000007
#define mx 100005
using namespace std;

struct matrix
{
    long long a[2][2];
};

matrix multiply (matrix x,matrix y)
{
    matrix t;
    for(int i=0; i<2; ++i)
        for(int j=0; j<2; ++j)
        {
            t.a[i][j]=0;
            for(int k=0; k<2; ++k)
                t.a[i][j]=(t.a[i][j]+x.a[i][k]*y.a[k][j]%mod+mod)%mod;
        }
    return t;
}

matrix powmatrix (matrix x,long long y)
{
    matrix t,temp;
    for(int i=0; i<2; ++i)
        for(int j=0; j<2; ++j)
        {
            if(i==j)
                t.a[i][j]=1;
            else
                t.a[i][j]=0;
        }
    temp=x;
    while(y)
    {
        if(y&1)
            t=multiply(t,temp);
        y>>=1;
        temp=multiply(temp,temp);
    }
    return t;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("1.txt","r",stdin);
#endif // ONLINE_JUDGE
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    long long x,y;
    long long n,ans;
    matrix a,t;
    while(cin>>x>>y)
    {
        cin>>n;

        a.a[0][0]=1;
        a.a[0][1]=-1;
        a.a[1][0]=1;
        a.a[1][1]=0;

        if(n==1)
         {
          cout<<((x%mod)+mod)%mod<<endl;
          continue;
         }
         if(n==2)
         {
           cout<<((y%mod)+mod)%mod<<endl;
           continue;
         }

        t=powmatrix(a,n-2);

        ans = t.a[0][0]*y%mod+t.a[0][1]*x%mod;
        ((ans%=mod)+=mod)%=mod;

        cout<<ans<<endl;

    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

渴鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值