HDU 2842(数论,构造矩阵)

Chinese Rings

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 218    Accepted Submission(s): 126

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.
 

 

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个环要拿下来必需前n-2要拿下来,然后在将第n个环拿下来f(n-2)+1 第n-1个环要拿下,则前n-2要放上去f(n-2),然后拿下前n-3再将n-1拿下f(n-3)+1,在将n-3放上去 f(n-3)。。。。一直循环得到:f(n)=f(n-2)+1+f(n-2)+f(n-3)+1+f(n-3)+......+f(n-n); 于是递推公式为:f(n)=2*f(n-2)+f(n-1)+1; 显然是构造二分矩阵求解。 f(n) 1 2 1 f(n-1) f(n-1) 1 0 0 f(n-2) 1 0 0 1 1 ************************************************************************/ #include <iostream> using namespace std; #define N 3 #define ll __int64 #define MOD 200907 struct Mat { ll martix[N][N]; }; Mat res,q,tp,tp1,tp2,tp3; void er_fun(int x) { int i,j,k,flag=0; tp1=q; tp=res; while (x) { if(x&1) { flag=1; memset(tp2.martix,0,sizeof(tp2.martix)); for (i=0;i<N;i++) { for (j=0;j<N;j++) { for(k=0;k<N;k++) { tp2.martix[i][j]+=(tp.martix[i][k]*tp1.martix[k][j])%MOD; tp2.martix[i][j]%=MOD; } } } } memset(tp3.martix,0,sizeof(tp3.martix)); for (i=0;i<N;i++) { for (j=0;j<N;j++) { for(k=0;k<N;k++) { tp3.martix[i][j]+=(tp1.martix[i][k]*tp1.martix[k][j])%MOD; } } } if(flag) tp=tp2; tp1=tp3; x>>=1; } } int main() { int i,j; ll n,sum; for (i=0;i<N;i++) { for (j=0;j<N;j++) { res.martix[i][j]=(i==j); } } q.martix[0][0]=q.martix[1][0]=q.martix[0][2]=q.martix[2][2]=1; q.martix[1][1]=q.martix[1][2]=q.martix[2][0]=q.martix[2][1]=0; q.martix[0][1]=2; while (scanf("%I64d",&n),n) { if(n==1 || n==2) { printf("%I64d/n",n); continue; } er_fun(n-2); sum=(tp.martix[0][0]*2+tp.martix[0][1]+tp.martix[0][2])%MOD; printf("%I64d/n",sum); } return 0; }

你可能感兴趣的:(HDU 2842(数论,构造矩阵))