三部曲一(搜索、数学)-1016-Code

Code

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 60000/30000K (Java/Other)
Total Submission(s) : 11   Accepted Submission(s) : 10
Problem Description
Transmitting and memorizing information is a task that requires different coding systems for the best use of the available space. A well known system is that one where a number is associated to a character sequence. It is considered that the words are made only of small characters of the English alphabet a,b,c, ..., z (26 characters). From all these words we consider only those whose letters are in lexigraphical order (each character is smaller than the next character). 

The coding system works like this: 
The words are arranged in the increasing order of their length. 
The words with the same length are arranged in lexicographical order (the order from the dictionary). 
We codify these words by their numbering, starting with a, as follows: 
a - 1 
b - 2 
... 
z - 26 
ab - 27 
... 
az - 51 
bc - 52 
... 
vwxyz - 83681 
... 

Specify for a given word if it can be codified according to this coding system. For the affirmative case specify its code. 
 

 

Input
The only line contains a word. There are some constraints: 
The word is maximum 10 letters length 
The English alphabet has 26 characters. 
 

 

Output
The output will contain the code of the given word, or 0 if the word can not be codified.
 

 

Sample Input
bf
 

 

Sample Output
55
 

 

Source
PKU

 

 

很久没写数位dp了,写这道题还要看着模板写。。。

用记忆化搜索写,套模板很好写

 

 

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string>
 4 #include <cstring>
 5 
 6 using namespace std;
 7 
 8 int length,digit[11],table[11][27];  //table[i][j]代表长度为i以数字j代表的字母开头的情况
 9 char code[11];
10 
11 int dfs(int len,bool bound,int low,bool zero,int head)  //zero代表是否有前导零,low代表循环的下届
12 {
13     if(len==0)
14         return zero?0:1;            //排除全是0的情况
15     if(!zero&&!bound&&table[len][head]!=-1)            
16         return table[len][head];
17     int up=bound?digit[len]:26;
18     int ret=0;
19     for(int i=low;i<=up;i++)
20     {
21         ret+=dfs(len-1,bound&&i==up,(zero&&i==0)?0:i+1,zero&&i==0,i);
22     }
23     if(!zero&&!bound)
24         table[len][head]=ret;
25     return ret;
26 }
27 
28 int fun()
29 {
30     int i;
31     for(i=0;i<length;i++)
32     {
33         digit[length-i]=code[i]-'a'+1;
34     }
35     return dfs(length,true,0,true,0);
36 }
37 
38 int main()
39 {
40     memset(table,-1,sizeof(table));
41     scanf("%s",code);
42     int ans,i;
43     length=strlen(code);
44     bool f=true;
45     for(i=0;i<length-1;i++)    //如果无法产生结果,ans=0
46         if(code[i]>code[i+1])
47             f=false;
48     if(!f)
49         ans=0;
50     else
51         ans=fun();
52     printf("%d\n",ans);
53     return 0;
54 }

 

posted @ 2013-11-27 18:59  Al J  阅读(223)  评论(0编辑  收藏  举报