codevs 3332 数列(矩阵快速幂)

来源:互联网 发布:和淘宝直播合作价格 编辑:程序博客网 时间:2024/06/05 17:59

go to the problem

题目描述 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

数据范围及提示 Data Size & Hint

对于30%的数据 n<=100;

对于60%的数据 n<=2*10^7;

对于100%的数据 T<=100,n<=2*10^9;

由于题目是用前面的项推后面的项,再加上数据范围很大,所以用矩阵快速幂做;

a[1]=a[2]=a[3]=1

a[x]=a[x-3]+a[x-1] (x>3)

求第n项。
由于 a[x]=a[x-3]+a[x-1],所以可知矩阵里有a[x-3],a[x-1].
个人喜好,把矩阵(b)定义为

a[x-2]
a[x-1]
a[x]

可知,递推用矩阵(a)为

0 1 0
0 0 1
1 0 1

目标矩阵(c) c[i][j]+=a[i][k]*b[k][j]

代码

#include<iostream>#include<cstdio>#include<cmath>#include<algorithm>#include<cstring>using namespace std;int N,p=1e9+7,T;struct maple{  long long a[4][4];    };maple multiply(maple A,maple B)//快速幂{    maple C;    memset(C.a,0,sizeof(C.a));    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]%p+(A.a[i][k]%p*B.a[k][j]%p)%p)%p;    return C;    }maple Done(int n){    maple x,Sum;    memset(x.a,0,sizeof(x.a));    memset(Sum.a,0,sizeof(Sum.a));    x.a[1][2]=x.a[2][3]=x.a[3][1]=x.a[3][3]=1;// 定义转移用矩阵    Sum.a[1][1]=Sum.a[2][1]=Sum.a[3][1]=1; // 定义初始矩阵 a[1] a[2] a[3]    while(n){        if(n&1) Sum=multiply(x,Sum);        x=multiply(x,x);        n>>=1;    }     return Sum;}int main(){   scanf("%d",&T);   while(T--)   {       scanf("%d",&N);       if(N>3)       {          maple Ans=Done(N-3);          cout<<Ans.a[3][1]%p<<'\n';       }       else cout<<1<<'\n';   }       return 0;}

PS: 真好玩

原创粉丝点击