Chinese Rings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 837 Accepted Submission(s):
480
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
Source
Recommend
根据题意推理。设f[n]表示拆掉前n个环需要的步数
显然要先把前n-2个拿掉:f[n-2]
拿掉第n个:1步
剩下第n-1个,如果要拆它,那么第n-2个必须挂着,根据题目意思,需要把前n-2个再次挂上,接下来的就是f[n-1]
f[n] = 2 * f[n - 2] + f[n - 1] + 1
然后推出系数矩阵,矩阵快速幂即可
拿掉第n个:1步
剩下第n-1个,如果要拆它,那么第n-2个必须挂着,根据题目意思,需要把前n-2个再次挂上,接下来的就是f[n-1]
f[n] = 2 * f[n - 2] + f[n - 1] + 1
然后推出系数矩阵,矩阵快速幂即可
| 1 0 0| | 1 | | 1 |
| 0 0 1| * | f[n-2] | = |f[n-1]|
| 1 2 1| | f[n-1] | | f[n] |
题意:如果前k个环被拆掉,第k+1个还被挂着,那么第k+2个就可以拿下或者装上,1可以任意挂取,按照这个要求取下所有的环。
附上代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #define mod 200907 5 using namespace std; 6 struct mat 7 { 8 long long m[3][3]; 9 }; 10 11 mat mul(mat a,mat b) 12 { 13 mat c; 14 int i,j,k; 15 memset(c.m,0,sizeof(c.m)); 16 for(i=0; i<3; i++) 17 for(j=0; j<3; j++) 18 { 19 for(k=0; k<3; k++) 20 c.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod; 21 c.m[i][j]%=mod; 22 } 23 return c; 24 } 25 26 mat product(mat a,int k) 27 { 28 if(k==1) return a; 29 else if(k&1) return mul(product(a,k-1),a); 30 else return product(mul(a,a),k/2); 31 } 32 33 int main() 34 { 35 int n,m,i,j; 36 mat a,b; 37 int x[4]= {1,1,2}; 38 while(~scanf("%d",&n)&&n) 39 { 40 if(n<3) 41 { 42 printf("%d ",x[n]%mod); 43 continue; 44 } 45 memset(a.m,0,sizeof(a.m)); 46 a.m[0][0]=1; 47 a.m[1][2]=1; 48 a.m[2][0]=1; 49 a.m[2][1]=2; 50 a.m[2][2]=1; 51 b=product(a,n-2); 52 long long ans=0; 53 for(i=0; i<3; i++) 54 ans+=(b.m[2][i]*x[i])%mod; 55 printf("%I64d ",ans%mod); 56 } 57 return 0; 58 }