跳到正文

题解

题解:P5136 sequence

Daemon0x52约 5 分钟
原文

这是 2025年11月14日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月13日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 5 分钟
题目
P5136

版本

  1. v2当前
  2. v1

思路

这个形式很容易联想到 Fibonacci 数列通项公式:

an=15((1+52)n−(1−52)n)a_n = \frac{1}{\sqrt{5}} \Big( (\frac{1 + \sqrt{5}}{2})^n - (\frac{1 - \sqrt{5}}{2})^n \Big)

令 x=1+52,y=1−52x = \frac{1 + \sqrt{5}}{2} , y = \frac{1 - \sqrt{5}}{2},则有计算方式 xn=an−ynx^n = a_n - y^n,由于 y=1−52∈(−1,0)y = \frac{1 - \sqrt{5}}{2} \in (-1 , 0),对答案的影响只与 nn 的奇偶性有关,所以答案是简单的:

xn=an−1+an−2+[2∤n] x_n = a_{n - 1} + a_{n - 2} + [ 2 \nmid n ]

考虑乘法公式:

xn+yn=(x+y)(xn−1+yn−1)+xy(xn−2+yn−2)x ^ n + y ^ n = ( x + y )( x ^ { n - 1 } + y ^ { n - 1 } ) + x y ( x ^ { n - 2 } + y ^ { n - 2 } )

其中 x+y=1,xy=−1x + y = 1 , x y = - 1,正确性得到了证明,接下来对 ana_n 使用矩阵快速幂即可,注意特判 n=1n = 1 或者 n=2n = 2。

Code

C++
#include<iostream>
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
const int MOD=998244353;
struct Matrix 
{
    long long data[2][2];
    Matrix() 
    {
        data[0][0]=data[0][1]=data[1][0]=data[1][1]=0;
    }
    Matrix(long long a00,long long a01,long long a10,long long a11) 
    {
        data[0][0]=a00;
        data[0][1]=a01;
        data[1][0]=a10;
        data[1][1]=a11;
    }
    Matrix operator*(const Matrix& other)const 
    {
        Matrix result;
        result.data[0][0]=(data[0][0]*other.data[0][0]%MOD+data[0][1]*other.data[1][0]%MOD)%MOD;
        result.data[0][1]=(data[0][0]*other.data[0][1]%MOD+data[0][1]*other.data[1][1]%MOD)%MOD;
        result.data[1][0]=(data[1][0]*other.data[0][0]%MOD+data[1][1]*other.data[1][0]%MOD)%MOD;
        result.data[1][1]=(data[1][0]*other.data[0][1]%MOD+data[1][1]*other.data[1][1]%MOD)%MOD;
        return result;
    }
    long long* operator[](long long index)
    {
        return data[index];
    }
    const long long* operator[](long long index)const 
    {
        return data[index];
    }
};
Matrix Quick_Pow(Matrix a,long long b)
    {
        Matrix res(1,0,0,1),base=a;
        while(b)
        {
            if(b&1) res=res*base;
            base=base*base;
            b>>=1;
        }
        return res;
    }
int T;
long long n;
int main()
{
    IOS;
    cin>>T;
    while(T--)
    {
        cin>>n;
        if(n==0)
        {
            cout<<1<<'\n';
            continue;
        }
        if(n==1)
        {
            cout<<2<<'\n';
            continue;
        }
        Matrix Base(1,1,1,0),ans(3,1,0,0);
        cout<<((ans*Quick_Pow(Base,n-2)).data[0][0]+(n&1))%MOD<<'\n';
    }
    return 0;
}