Chinese Rings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 986 Accepted Submission(s): 574
Problem Description
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.
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
题意:有n个环,如果要(拆除/挂上)第k+2个环,则必须先拆除前k个环,且第k+1个环要挂上
问拆除所有环需要多少步骤
题解:首先要理解本题最重要的一点:拆除前x个环和挂上前x个环的花费是相同的
设f[x]为拆除前x个环所需步骤;
①首先拆除前x-2个环,花费f[x-2];
②再拆除第x个环,花费1;
③为了拆除第x-1个环,应挂上第x-2个环,由于前x-2个环全部拆除,因此挂上前x-2个环花费f[x-2];
④拆除前x-1个环花费f[x-1]
于是总花费f[n]=f[n-1]+2*f[n-2]+1
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 200907;
const int sz = 3;
struct Mat{
LL x[sz][sz];
Mat(){
memset(x,0,sizeof(x));
}
void init(){
for(int i=0;i<sz;i++) x[i][i]=1;
}
Mat operator*(const Mat &m)const{
Mat ret;
for(int i=0;i<sz;i++)
for(int j=0;j<sz;j++)
for(int k=0;k<sz;k++)
ret.x[i][j]=(ret.x[i][j]+x[i][k]*m.x[k][j])%mod;
return ret;
}
};
Mat pow(Mat A,LL n){
Mat ret;
ret.init();
while(n){
if(n&1) ret=ret*A;
A=A*A;
n>>=1;
}
return ret;
}
LL solve(LL n){
if(n==1) return 1;
if(n==2) return 2;
Mat A,B;
A.x[0][0]=1;A.x[0][1]=2;A.x[0][2]=1;
A.x[1][0]=1;
A.x[2][2]=1;
B.x[0][0]=2;
B.x[1][0]=1;
B.x[2][0]=1;
A=pow(A,n-2);
LL ret=(A*B).x[0][0];
return ret;
}
int main(){
LL n;
while(scanf("%lld",&n),n){
printf("%lld\n",solve(n));
}
return 0;
}