ACM: 动态规划题 poj 2033 (博客好…

来源:互联网 发布:mac安装jdk 编辑:程序博客网 时间:2024/06/04 19:04
Alphacode

 

Description

Alice and Bob needto send secret messages to each other and are discussing ways toencode their messages:
Alice: "Let's just use a very simple code: We'll assign'A' the code word 1, 'B' will be 2, and so on down to 'Z' beingassigned 26."
Bob: "That's a stupid code, Alice. Suppose I send you the word'BEAN' encoded as 25114. You could decode that in many differentways!”
Alice: "Sure you could, but what words would you get? Other than'BEAN', you'd get 'BEAAD', 'YAAD', 'YAN', 'YKD' and 'BEKD'. I thinkyou would be able to figure out the correct decoding. And why wouldyou send me the word ‘BEAN’ anyway?”
Bob: "OK, maybe that's a bad example, but I bet you that if you gota string of length 500 there would be tons of different decodingsand with that many you would find at least two different ones thatwould make sense."
Alice: "How many different decodings?"
Bob: "Jillions!"

For some reason, Alice is still unconvinced by Bob's argument, soshe requires a program that will determine how many decodings therecan be for a given string using her code.

Input

Input will consistof multiple input sets. Each set will consist of a single line ofdigits representing a valid encryption (for example, no line willbegin with a 0). There will be no spaces between the digits. Aninput line of '0' will terminate the input and should not beprocessed

Output

For each input set,output the number of possible decodings for the input string. Allanswers will be within the range of a long variable.

Sample Input

25114
1111111111
3333333333
0

Sample Output

6
89
1

 

题意: 现在要你做一项译码工作,A=1,B=2,C=3,...,Z=26.

     现在给你一串数字要求你求出可以组成的字符串个数.

解题思路:

    1.设状态: dp[i]:表示前i个数字可以组成不同的字符串的个数.

    2.仔细观察就会发现, (我们保证输入是有意义的,即:100,1002,1890之类不会出现)

          (1)当str[i]=='0'时,并且str[i-1] == '1' || str[i-1] == '2'时,dp[i] = dp[i-2];

            这是显然的,因为当前str[i]是0, 即str[i-1]*10+str[i]必然翻译成一个字符.

         (2)当str[i]!='0'时, 显然我们可以先确定出, dp[i]=dp[i-1];因为当前str[i]可以独立翻译

            如果temp = str[i-1]*10+str[i],11<=temp<=26, 显然这样可以翻译成不同的字符串.

            dp[i] = dp[i]+dp[i-2];

代码:

#include<cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 50005

int dp[MAX];
char str[MAX];

int main()
{
// freopen("input.txt","r",stdin);
 while(scanf("%s",str+1) != EOF)
 {
  if(strcmp(str+1,"0") == 0)break;
  int len = strlen(str+1);

  dp[0] = dp[1] =1;

  for(int i = 2; i<= len; ++i)
  {
   if(str[i] =='0')
   {
    dp[i]= dp[i-2];
   }
   else
   {
    dp[i]= dp[i-1];
    inttemp = (str[i-1]-'0')*10+(str[i]-'0');
    if(temp>= 11 && temp<= 26) dp[i] += dp[i-2];
   }
  }
  printf("%d\n",dp[len]);
 }
 
 return 0;
}

0 0
原创粉丝点击