Chinese Rings 矩阵快速幂

题意:把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.
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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值