Code[VS]3332 数列

来源:互联网 发布:淘宝生意参谋情报竞争 编辑:程序博客网 时间:2024/05/23 19:16

Description
a[1]=a[2]=a[3]=1
a[x]=a[x-3]+a[x-1] (x>3)
求a数列的第n项对1000000007(10^9+7)取余的
值。
Input Description
第一行一个整数T,表示询问个数。
以下T行,每行一个正整数n。
Output Description
每行输出一个非负整数表示答案
Sample Input
3
6
8
10
Sample Output
4
9
19

这道题表面是暴力,但实际上看它的数据,我相信大家会很灰心。所以,我们要采用矩阵乘法这个神奇的东西来加速。同时也要用快速幂辅助它。公式为{0,1,0}{0,0,1}{1,0,1}*{f1 f2 f3}={f2 f3 f4}。推得公式后,题目就变简单。之后的,都是套路了。

#include<cstdio>#include<cstdlib>#include<algorithm>#include<cmath>#include<cstring>using namespace std;struct node{    long long a[5][5];    node()    {        memset(a,0,sizeof(a));    }};node pre,f;node chengfa(node a,node b){    node c;    for(int i=1;i<=3;i++)    {        for(int j=1;j<=3;j++)        {            for(int k=1;k<=3;k++)            {                c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j])%1000000007;            }        }    }    return c;}int main(){    long long n,x;    scanf("%lld",&n);    while(n--)    {        scanf("%lld",&x);        if(x<=3){printf("1\n");continue;}        x-=3;        pre.a[1][1]=pre.a[1][3]=pre.a[2][1]=pre.a[2][2]=pre.a[3][2]=0;        pre.a[1][2]=pre.a[2][3]=pre.a[3][1]=pre.a[3][3]=1;        f.a[1][1]=f.a[2][1]=f.a[3][1]=1;        while(x>0)        {            if(x%2==1)f=chengfa(pre,f);            pre=chengfa(pre,pre);            x/=2;        }        printf("%lld\n",f.a[3][1]%1000000007);    }    return 0;}
2 0
原创粉丝点击