hrbust Final Destination II
找出递推公式为an=an-1+an-2+an-3;
用到的是快速幂与矩阵乘法。
快速幂:求a的b次方时可直接用:
int res=1;
while(b){
if(b&1)//判断b是否为奇数;
res=a*res;
a=a*a;
b/=2;
}
return res;
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 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
1 #include<stdio.h> 2 #include<string.h> 3 #define mod 1000000007 4 long long stairs[3][3]; 5 void multy(long long a[][3],long long b[][3])//矩阵的乘法 6 { 7 long long i, j, k; 8 long long c[3][3]; 9 for(i = 0; i < 3; i++) 10 for(j = 0; j < 3; j++){ 11 c[i][j] = 0; 12 for(k = 0; k < 3; k++){ 13 c[i][j] += ((a[i][k]%mod)*(b[k][j]%mod))%mod; 14 } 15 } 16 for(i = 0; i < 3; i++)//将结果返回给b[][]; 17 for(j = 0; j < 3; j++) 18 b[i][j] = c[i][j]%mod; 19 } 20 long long ultim(long long n,long long a[][3],long long b[][3]) 21 { 22 while(n)//矩阵的快速幂求法 23 { 24 if(n&1) 25 multy(a,b); 26 multy(a,a); 27 n/=2; 28 } 29 return b[0][0]; 30 } 31 int main() 32 { 33 long long n,k=1,t; 34 scanf("%lld",&t); 35 while(t--) 36 { 37 scanf("%lld",&n); 38 memset(stairs,0,sizeof(stairs)); 39 stairs[0][0]=4;stairs[1][0]=2;stairs[2][0]=1; 40 long long coeff[3][3]={1,1,1,1,0,0,0,1,0}; 41 //multy(coeff,coeff); 42 printf("Case %lld:\n",k++); 43 if(n==0) 44 printf("1\n"); 45 else if(n == 1) 46 printf("1\n"); 47 else if(n == 2) 48 printf("2\n"); 49 else 50 printf("%lld\n",ultim(n-3,coeff,stairs)); 51 } 52 return 0; 53 }
|