[codevs4267]阮神的妹子们

时间限制: 1 s
空间限制: 128000 KB

题目描述 Description

阮神最近又找到了一些妹子并且把她们都叫到了机房站成一队,其中第一到第三个妹子身高为1,从第四个开始身高就是前一个妹子(第三个)和前第三个妹子(第一个)的身高之和求他的第n个妹子的身高对(10^9+7)取模的结果

输入描述 Input Description

第一行一个整数T,表示询问个数。
以下T行,每行一个正整数n。

输出描述 Output Description

每行输出一个非负整数表示答案。

样例输入 Sample Input

3
6
8
10

样例输出 Sample Output

4
9
19

数据范围及提示

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

题解:简述题意
f [ i ] = 1 ( 0 < i < = 3 ) , f [ i ] = f [ i - 1 ] + f[ i - 3 ] ( i > 3 )
对于输入的每一个n求f [ n ] % 1000000007 的答案
那么只需要一个简单的矩阵快速幂就搞定了。

#include
#include
#include
#include
#define MOD 1000000007
#define LiangJiaJun main
#define LL long long
using namespace std;
struct Matrix{
    LL a[4][4];
}T,G;
int t,n;
void reset(){
     memset(G.a,0,sizeof(G.a));
     memset(T.a,0,sizeof(T.a));
     G.a[1][1]=1;G.a[1][2]=1;G.a[1][3]=1;
     T.a[1][1]=1;T.a[1][2]=1;
                             T.a[2][3]=1;
     T.a[3][1]=1;
     return ;
}
Matrix mul(Matrix x,Matrix y){
    Matrix ans;
    memset(ans.a,0,sizeof(ans.a));
    for(int i=1;i<=3;i++)
        for(int j=1;j<=3;j++)
            for(int k=1;k<=3;k++){
                LL temp=(x.a[i][k]*y.a[k][j])%MOD;
                ans.a[i][j]=(ans.a[i][j]+temp)%MOD;
            }
    return ans;
}
Matrix fastpow(Matrix s,int p){
    if(p == 1) return s;
    Matrix temp=fastpow(s,p>>1);
    if(p&1)return mul(mul(temp,temp),s);
    return mul(temp,temp);
}
int LiangJiaJun (){
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        reset();
        if(n <= 3){cout<<1<continue;}
        G=mul(G,fastpow(T,n-3));
        printf("%lld\n",G.a[1][1]);
    }
    return 0;
}

你可能感兴趣的:(递推)