hrbust 1126 HLG 矩阵快速幂

来源:互联网 发布:dell校色软件 编辑:程序博客网 时间:2024/05/14 07:31

再来一个模板题

这题也是找递推的矩阵

111100010Final Destination IITime Limit: 1000 MSMemory Limit: 65536 KTotal Submit: 392(116 users)Total Accepted: 157(89 users)Rating: Special Judge: NoDescription

JiaoZhu likes going on adventure! One day, he walks into a big castle, and there is an unique stairway. JiaoZhu finds a board ,it says “The one who want to go upstairs only can go three steps the most once, meaning that you can go 1 or 2 or 3 steps once!”. Now, we have a problem, can you tell me the number of ways to go to the destination? If you can’t ,death is the only choice

In the beginning, you are in the 0th step. 

Input

First input a integer T(T<50), represent the number of case.

Each case ,the input will consist only a positive integer n (0<=n<=1000000000), represent the nth steps you want to go to..

Output

Order the sample output format to output.

Line 1,print the Case k.

Line 2,print one integer represent the number of ways to go to nth steps.(MOD 1000000007)

Sample Input
2
1
2
Sample Output
Case 1:
1
Case 2:
2
Hint

When n=2,you can go one step once to go to 2th ,or go 2 steps once to 2th,so the answer is 2.

Author齐达拉图
#include<stdio.h>#define MOD 1000000007#define ll long longstruct nana{    ll  m[3][3];}h,l;nana juzhen(nana a,nana b){    nana temp;    for(int i=0;i<3;i++)    {        for(int j=0;j<3;j++)        {            temp.m[i][j]=0;            for(int k=0;k<3;k++)            {                temp.m[i][j]=(temp.m[i][j]+a.m[i][k]*b.m[k][j])%MOD;            }        }    }    return temp;}ll zzz(ll n){    for(int i=0; i<3; i++)    {        for(int j=0; j<3; j++)        {            if(i==j)            h.m[i][j]=1;            else h.m[i][j]=0;        }    }    l.m[0][0]=l.m[0][1]=l.m[0][2]=l.m[1][0]=l.m[2][1]=1;    l.m[1][1]=l.m[1][2]=l.m[2][0]=l.m[2][2]=0;    while(n)    {        if(n%2==1)            h=juzhen(h,l);        l=juzhen(l,l);        n=n/2;    }    return h.m[0][0];}int main(){    ll k=0;    ll n;    int t;    scanf("%d",&t);    while(t--){    scanf("%lld",&n);        printf("Case %lld:\n",++k);        printf("%lld\n",zzz(n));}}


0 0