Dumbear likes to play the Chinese Rings (Baguenaudier). It’s a game played with nine rings on a bar. The rules of this game are very simple: At first, the nine rings are all on the bar.
The first ring can be taken off or taken on with one step.
If the first k rings are all off and the (k + 1)th ring is on, then the (k + 2)th ring can be taken off or taken on with one step. (0 ≤ k ≤ 7)
Now consider a game with N (N ≤ 1,000,000,000) rings on a bar, Dumbear wants to make all the rings off the bar with least steps. But Dumbear is very dumb, so he wants you to help him.
Input
Each line of the input file contains a number N indicates the number of the rings on the bar. The last line of the input file contains a number "0".
Output
For each line, output an integer S indicates the least steps. For the integers may be very large, output S mod 200907.
Sample Input
1
4
0
Sample Output
1
10
思路:这道题可以用矩阵快速幂来做,首先推出规律是Fn=F(n-1)+2F(n-2)+1,根据这个公式,可以设计出a,b两个矩阵相乘为
当n=0时,F1=1,F0=0,即
所以 只要求出b矩阵的n-1次方就可以了,用快速幂的方法求省时间,相乘时初始值为单位矩阵。
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
typedef struct node
{
long long int t[3][3];
}q;
q a,b,c;
q ride(q c,q r)//矩阵相乘
{
q d;
memset(d.t,0,sizeof(d.t));
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
for(int k=0; k<3; k++)
{
d.t[i][j]=(d.t[i][j]+c.t[i][k]*r.t[k][j])%200907;
}
}
}
return d;
}
q m(int k)//快速幂
{
while(k)
{
if(k & 1)
a = ride(a,b);
b = ride(b, b);
k >>= 1;
}
return a;
}
int main()
{
long long int n;
while(cin>>n&&n!=0)
{
memset(a.t,0,sizeof(a.t));
memset(b.t,0,sizeof(b.t));
a.t[0][0]=a.t[1][1]=a.t[2][2]=b.t[0][0]=b.t[0][1]=b.t[2][0]=b.t[2][2]=c.t[0][0]=c.t[0][2]=1;
b.t[1][0] = 2;
int k=n-1;
q f=m(k);
f=ride(c,f);
cout<<f.t[0][0]%200907<<endl;
}
return 0;
}