Sicily 1001. Alphacode

本文介绍了一种使用动态规划算法解决密码子字符串解密问题的方法。对于特定的字符组合,文章详细阐述了如何通过递推公式计算可能的解密方案数量。

动态规划题目,若第i个字符能够和前一个字符构成有意义的密码,即10-26,则这个字符前(包括这个字符)的子字符串可以构成的可能解有dp[i] =dp[i-1]+dp[i-2]个,因为此时:这个字符可以单独作为一个密码存在,此时整个子字符串有dp[i-1]个解;又或者是和前一个字符作为一个密码存在,此时整个字符串有dp[i-2]个解。若第i个字符无法和其前一个字符构成有意义的密码,那么这个字符只能作为一个单独的密码存在,此时整个子字符串有dp[i-1]个解。若当前字符是0,由于密码的正确性,其前一个字符必定是0或者1,此时整个子字符串有dp[i-2]个解。另外数组要开得大点,因为题目中没有说明字符串最大有多大,也可以只设3个变量来解决这个问题,毕竟这个动态转移方程和斐波纳兹函数很像。

Run Time: 0sec                                                                        

Run Memory: 312KB

Code length: 651Bytes

SubmitTime: 2012-02-0121:54:13

// Problem#: 1001
// Submission#: 1204017
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int i;
    string s;
    int num[ 3 ];

    while ( cin >> s && s != "0" ) {
        num[ 0 ] = num[ 1 ] = num[ 2 ] = 1;
        for ( i = 1; i < s.size(); i++ ) {
            num[ 0 ] = num[ 1 ];
            num[ 1 ] = num[ 2 ];
            if ( s[ i ] == '0' )
                num[ 2 ] = num[ 0 ];
            else if ( ( s[ i - 1 ] == '1' && s[ i ] <= '9' ) || ( s[ i - 1 ] == '2' && s[ i ] <= '6' ) )
                num[ 2 ] = num[ 0 ] + num[ 1 ];
            else
                num[ 2 ] = num[ 1 ];
        }
        cout << num[ 2 ] << endl;
    }

    return 0;

}                                 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值