题意:把n个环拆下来的最小步骤
操作:第一个环可一步取走或戴上,要取走或戴上第n个环,前n-2个环必须取走,且第n-1个环还在;
思路:设取走前n个环要f[n]步,此时前n-2个环已取走,因此f[n]=f[n-2]+1,取走第n个环走一步。
要取第n-1个环,先把前n-2个环加上,f[n-2]步,再取走前n-1个环,走f[n-1]步;
所以f[n]=f[n-2]+1+f[n-2]+f[n-1]=f[n-1]+2*f[n-2]+1;
1 2 1 f[n-1] f[n]
1 0 0 f[n-2] f[n-1]
0 0 1 1 1
建立递推式,轻松加愉快。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int n=3,mod=200907;
struct matrix
{
ll mat[n][n];
matrix operator *(const matrix &b)
{
matrix tp;
memset(tp.mat,0,sizeof(tp.mat));
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
{
tp.mat[i][j]+=mat[i][k]*b.mat[k][j];
tp.mat[i][j]%=mod;
}
return tp;
}
};
int power(int k)
{
if(k<=2) return k%mod;
k-=2;
matrix base={1,2,1,1,0,0,0,0,1},ans;
memset(ans.mat,0,sizeof(ans.mat));
for(int i=0;i<n;i++)
ans.mat[i][i]=1;
while(k){
if(k&1) ans=ans*base;
base=base*base;
k>>=1;
}
return (2*ans.mat[0][0]+ans.mat[0][1]+ans.mat[0][2])%mod;
}
int main()
{
int k;
while(scanf("%d",&k)&&k)
printf("%d\n",power(k));
return 0;
}
题目:
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.
1 4 0
1 10