2017 ACM/ICPC Asia Regional Shenyang Online E题【number number number】--矩阵快速幂与斐波那契数列

来源:互联网 发布:oppo手机解压软件 编辑:程序博客网 时间:2024/06/05 17:06

number number number

Problem Description
We define a sequence F:

 F0=0,F1=1;
 Fn=Fn1+Fn2 (n2).

Give you an integer k, if a positive number n can be expressed by
n=Fa1+Fa2+...+Fak where 0a1a2ak, this positive number is mjfgood. Otherwise, this positive number is mjfbad.
Now, give you an integer k, you task is to find the minimal positive mjfbad number.
The answer may be too large. Please print the answer modulo 998244353.
Input
There are about 500 test cases, end up with EOF.
Each test case includes an integer k which is described above. (1k109)
Output
For each case, output the minimal mjfbad number mod 998244353.

Sample Input
1
Sample Output
4
Source
2017 ACM/ICPC Asia Regional Shenyang Online

解题新知:这道题题意弄明白,规律找出来后,即F[k] = f[2*k+3] -1,普通递推开那么大的数组会ME或TLE,和队友一直想怎么优化……没想到,居然有矩阵快速幂求斐波那契这种神奇的东西!数学之美啊

一篇比较好的讲解矩阵快速幂:矩阵快速幂求斐波那契数列(初学整理)


学过线性代数,原理很容易明白。就直接写代码了,未来还得好好加油。

AC代码:
#include<iostream>#include<cstring>#include<cstdio>const int MOD = 998244353;using namespace std;typedef struct node{    long long a[2][2];}matrix;matrix matMul(matrix x,matrix y) //矩阵乘法{    matrix res;    memset(res.a,0,sizeof(res.a));    for(int i=0;i<2;i++)    {        for(int j=0;j<2;j++)        {            for(int k=0;k<2;k++)            {                res.a[i][j]+=x.a[i][k]*y.a[k][j];                res.a[i][j]%=MOD;            }        }    }    return res;}long long pow(int p)  //矩阵快速幂{    matrix res;    matrix c;    memset(c.a,0,sizeof(c.a));    memset(res.a,0,sizeof(res.a));    for(int i=0;i<2;i++)        res.a[i][i] = 1;    c.a[0][0]=1,c.a[0][1]=1;    c.a[1][0]=1,c.a[1][1]=0;    while(p)    {        if(1&p) res = matMul(res,c);        c = matMul(c,c);        p>>=1;    }    return res.a[0][1];}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        printf("%lld\n",(pow(2*n+3)-1)%MOD);    }    return 0;}


阅读全文
0 0
原创粉丝点击