hdu 2842 Chinese Rings(动态规划+矩阵快速幂)

本文深入探讨了算法设计、数据结构、机器学习等领域的关键概念,并通过具体案例展示了这些技术的实际应用,旨在帮助读者更好地理解和掌握现代信息技术的核心原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Chinese Rings

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


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-2个灯关上,当这个灯关上后,第n-1个灯还未关上,那么关上第n-1个灯又是要先打开第n-2个灯,依次类推,因为灯的状态从全开到全关,与从全关到全开是一致的,所以这道题的公式就是f[n] = f[n-2]+1 + f[n-2] + f[n-1] 合并后就是 f[n] = f[n-1] + 2*f[n-2] + 1
那么转换成矩阵后就很容易求解了
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define MAX 3
#define MOD 200907

using namespace std;

typedef long long LL;

int n;

struct Matrix
{
    int  a[MAX][MAX];
    Matrix()
    {
        memset ( a , 0 , sizeof ( a ) );
    }
};

Matrix multi ( Matrix m1 , Matrix m2 )
{
    Matrix ret;
    for ( int i = 0 ; i < MAX ; i++ )
        for ( int j = 0 ; j < MAX ; j++ )
            if ( m1.a[i][j] )
                for ( int k = 0 ; k < MAX ; k++ )
                    ret.a[i][k] = ( ret.a[i][k] + ((LL)(m1.a[i][j])*(LL)(m2.a[j][k]))%MOD )%MOD;
    return ret;
}

Matrix quick ( Matrix m , int n )
{
    Matrix ret;
    for ( int i = 0 ; i < MAX ; i++ )
        ret.a[i][i] = 1;
    while ( n )
    {
        if ( n&1 ) ret = multi ( ret , m );
        m = multi ( m , m );
        n >>= 1;
    }
    return ret;
}

int main ( )
{
    while ( ~scanf ( "%d" , &n ) , n )
    {
        Matrix ans;
        ans.a[0][0] = ans.a[0][2] = 1;
        Matrix vary;
        vary.a[0][0] = vary.a[0][1] = vary.a[2][2] = vary.a[2][0] = 1;
        vary.a[1][0] = 2;
        vary = quick ( vary , n-1 );
        ans = multi ( ans , vary );
        printf ( "%d\n" , ans.a[0][0] );
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值