sicily_1001 alphacode

题目

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

Alice and Bob need to send secret messages to each other and are discussing ways to encode 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' being assigned 26." Bob: "That's a stupid code, Alice. Suppose I send you the word 'BEAN' encoded as 25114. You could decode that in many different ways!" Alice: "Sure you could, but what words would you get? Other than 'BEAN', you'd get 'BEAAD', 'YAAD', 'YAN', 'YKD' and 'BEKD'. I think you would be able to figure out the correct decoding. And why would you send me the word 'BEAN' anyway?" Bob: "OK, maybe that's a bad example, but I bet you that if you got a string of length 500 there would be tons of different decodings and with that many you would find at least two different ones that would make sense." Alice: "How many different decodings?" Bob: "Jillions!" For some reason, Alice is still unconvinced by Bob's argument, so she requires a program that will determine how many decodings there can be for a given string using her code.

Input

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

Output

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

Sample Input

25114
1111111111
3333333333
0

Sample Output

6
89
1

思路

  1. 将字符串读取后,扫描变成整型数组;
  2. 用dp[i]来保存分析到第i位的结果。对于第0位分解很简单,仅有1种;
  3. 对第1位进行分析:
    • 若第1位为零:结果只有合并一种;
    • 若第1位非零:判断是否能和第0位合并,若能,则为2种,否则为1种。
  4. 对2到n位的分析(假设分析到第k位,如果是第一位就特殊处理。):
    • 如果第k-1位与第k位能组成一个合法字母号:
      • 第k位为零:dp[i] = dp[i-2];
      • 第k位非零:有分开和合并两种情况,故dp[k] = dp[k-2]+dp[k-1];
    • 如果第k-1位与第k位不能组成一个合法字母号,则结果只有分开的情况,dp[k] = dp[k-1]。

合法字母号为1-26,如01、27、31则为不合法。

代码

// Copyright (c) HuangJunjie@SYSU(SNO:13331087). All Rights Reserved.
#include
#include

void getdigit(int* digit, char* str) {
  int i;
  for (i = 0; str[i]; i++) digit[i] = str[i] - '0';
}

long CC(int *digit, int END) {
  long dp[10000 + 1] = { 0 };

  dp[0] = dp[1] = 1;
  dp[1] = (digit[1] != 0 && (digit[0] * 10 + digit[1] <= 26)) ? 2 : 1;

  for (int i = 2; i < END; i++) {
    if ((digit[i-1] * 10 + digit[i] <= 26) && digit[i-1] != 0) {
      dp[i] = (digit[i] == 0 ? dp[i - 2] : dp[i - 2] + dp[i - 1]);
    } else {
      dp[i] = dp[i - 1];
    }
  }
  return dp[END-1];
}

int main() {
  char str[10000 + 10];
  int digit[10000 + 10];
  long long result;
  while (scanf("%s", str) && str[0] != '0') {
    getdigit(digit, str);
    result = CC(digit, strlen(str));
    printf("%lld\n", result);
  }
  return 0;
}

参考

http://www.cnblogs.com/mrlaker/archive/2012/07/17/2595271.html

你可能感兴趣的:(sicily_1001 alphacode)