Chinese Rings

 

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

思路:这道题可以用矩阵快速幂来做,首先推出规律是Fn=F(n-1)+2F(n-2)+1,根据这个公式,可以设计出a,b两个矩阵相乘为

当n=0时,F1=1,F0=0,即

 所以  只要求出b矩阵的n-1次方就可以了,用快速幂的方法求省时间,相乘时初始值为单位矩阵。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
typedef struct node
{
    long long int t[3][3];
}q;
q a,b,c;
q ride(q c,q r)//矩阵相乘
{
    q d;
    memset(d.t,0,sizeof(d.t));
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            for(int k=0; k<3; k++)
            {
                d.t[i][j]=(d.t[i][j]+c.t[i][k]*r.t[k][j])%200907;
            }
        }
    }
    return d;
}
q m(int k)//快速幂
{
    while(k)
    {
        if(k & 1)
            a = ride(a,b);
        b = ride(b, b);
        k >>= 1;
    }
    return a;
}

int main()
{
    long long int n;
    while(cin>>n&&n!=0)
    {
        memset(a.t,0,sizeof(a.t));
        memset(b.t,0,sizeof(b.t));
        a.t[0][0]=a.t[1][1]=a.t[2][2]=b.t[0][0]=b.t[0][1]=b.t[2][0]=b.t[2][2]=c.t[0][0]=c.t[0][2]=1;
        b.t[1][0] = 2;
        int k=n-1;
        q f=m(k);
        f=ride(c,f);
        cout<<f.t[0][0]%200907<<endl;
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值