HDU2842 矩阵乘法

时间:2022-10-08 11:13:48

Chinese Rings

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

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
 
Source
题意:
棍上有n个环,第一个环可以随时拿下或放上,只有在前k-2个环拿下了,第k-1个环在棍上才能拿下或放上第k个环,问把环全部拿下的最少步数。每拿下一个环或放上一个环用一步。
代码:
 /*
当环多于3个时,必然要先拿走最后一个,要想拿走最后一个就要先拿走前n-2个也就是需要f(n-2)步,然后才能
拿走最后一个,然后再把前n-2个加上又是f(n-2)步,才能继续拿,然后就是要算拿走n-1个环的步数,因此
递推公式:f(n)=f(n-2)+1+f(n-2)+f(n-1).然后构造矩阵,快速幂. 1 0 0^n-2 * 1
1 1 2 f(n-1)
0 1 0 f(n-2)
*/
#include<iostream>
using namespace std;
const int mod=;
struct Lu
{
long long A[][]; // long long
}L;
void init()
{
L.A[][]=L.A[][]=L.A[][]=L.A[][]=;
L.A[][]=L.A[][]=L.A[][]=L.A[][]=;
L.A[][]=;
}
Lu multi(Lu x,Lu y)
{
Lu z;
for(int i=;i<;i++)
for(int j=;j<;j++){
z.A[i][j]=;
for(int k=;k<;k++){
z.A[i][j]+=x.A[i][k]*y.A[k][j];
z.A[i][j]%=mod;
}
}
return z;
}
Lu solve(int x)
{
if(x==) return L;
if(x&){
Lu p=solve(x-);
return multi(p,L);
}
else {
Lu p=solve(x/);
return multi(p,p);
}
}
int main()
{
int n;
while(cin>>n&&n){
if(n==){
cout<<<<endl;
continue;
}
else if(n==){
cout<<<<endl;
continue;
}
init();
L=solve(n-);
int ans=(L.A[][]*)%mod+(L.A[][]*)%mod+(L.A[][]*)%mod;
cout<<ans%mod<<endl;
}
return ;
}