动态规划题目,若第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;
}
本文介绍了一种使用动态规划算法解决密码子字符串解密问题的方法。对于特定的字符组合,文章详细阐述了如何通过递推公式计算可能的解密方案数量。
1277

被折叠的 条评论
为什么被折叠?



