HLG 1126 Final Destination II 矩阵乘法+快速求幂

Description

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 0thstep. 

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
代码:
View Code
#include<stdio.h>
void multiply(__int64 x[][4],__int64 y[][4])
{ __int64 i,k,j,s[4][4];
for(i=1;i<=3;i++)
for(j=1;j<=3;j++)
{ s[i][j]=0;
for(k=1;k<=3;k++)
s[i][j]=s[i][j]+x[i][k]*y[k][j]; }
for(i=1;i<=3;i++)
for(j=1;j<=3;j++)
y[i][j]=s[i][j]%1000000007;
}
int main()
{ __int64 i,n,e[4][4],a[32][4][4],b[4][4];
int p,t;
e[1][1]=e[1][2]=e[1][3]=e[2][1]=e[3][2]=1;
e[2][2]=e[2][3]=e[3][1]=e[3][3]=0;
for(i=0;i<31;i++)//为快速求幂作准备
{ a[i][1][1]=e[1][1]; a[i][1][2]=e[1][2]; a[i][1][3]=e[1][3];
a[i][2][1]=e[2][1]; a[i][2][2]=e[2][2]; a[i][2][3]=e[2][3];
a[i][3][1]=e[3][1];a[i][3][2]=e[3][2]; a[i][3][3]=e[3][3];
multiply(e,e); }
p=0;
scanf("%d",&t);
while(t--)
{ p++;
scanf("%I64d",&n);
{ b[1][1]=4;b[2][2]=2;b[3][3]=1;
b[1][2]=b[1][3]=b[2][1]=b[2][3]=b[3][1]=b[3][2]=0;
for(i=0;i<31;i++)
if((n+1)&(1<<i)) //用快速求幂(按n的二进制数的每为是否为1求幂)原矩阵的n次方
multiply(a[i],b);
printf("Case %d:\n%d\n",p,b[1][3]); }
}
return 0;
}

转载于:https://www.cnblogs.com/dream-wind/archive/2012/03/16/2399628.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值