Word Index
Word Index |
Encoding schemes are often used in situations requiring encryption or information storage/transmission economy. Here, we develop a simple encoding scheme that encodes particular types of words with five or fewer (lower case) letters as integers.
Consider the English alphabet {a,b,c,...,z}. Using this alphabet, a set of valid words are to be formed that are in a strict lexicographic order. In this set of valid words, the successive letters of a word are in a strictly ascending order; that is, later letters in a valid word are always after previous letters with respect to their positions in the alphabet list {a,b,c,...,z}. For example,
abc aep gwz
are all valid three-letter words, whereas
aab are cat
are not.
For each valid word associate an integer which gives the position of the word in the alphabetized list of words. That is:
a -> 1 b -> 2 . . z -> 26 ab -> 27 ac -> 28 . . az -> 51 bc -> 52 . . vwxyz -> 83681
Your program is to read a series of input lines. Each input line will have a single word on it, that will be from one to five letters long. For each word read, if the word is invalid give the number 0. If the word read is valid, give the word's position index in the above alphabetical list.
Input
The input consists of a series of single words, one per line. The words are at least one letter long and no more that five letters. Only the lower case alphabetic {a,b,...,z} characters will be used as input. The first letter of a word will appear as the first character on an input line.
The input will be terminated by end-of-file.
Output
The output is a single integer, greater than or equal to zero (0) and less than or equal 83681. The first digit of an output value should be the first character on a line. There is one line of output for each input line.
Sample Input
z a cat vwxyz
Sample Output
26 1 0 83681
解题报告: 以前在POJ上记得做过相似的题目。在下一般都是比较害怕这种题目的,一般都是思路简单,处理复杂。
这题经过思考,发现不是那么难搞。首先,长度为1的串一共有C(26, 1)个,长度为2的串一共有C(26, 2)个(一大一小),依次类推。长度为5的串的序数要加上长度为1,2,3,4的串的总数。然后我们分析一下,以长度为3举例,例如dfg。看第一位d,那么我们可以发现首位为a,b,c的串都在它的前面,他们的序数需要加上去,首位为a的长度为3的串有C(25, 2)个,b的是C(24,2)个,c的是C(23,2)个。再看第二位f,在它前面的只有e了,类似处理,有C(21,1)个。这样加起来再加1就是答案了。另外判断一下当前位是否大于上一位,否则直接输出0。代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int C[27][6];
char str[6];
void init()
{
for(int i=0;i<=26;i++)
{
C[i][0]=1;
for(int j=1;j<=5;j++)
{
C[i][j] = C[i-1][j]+C[i-1][j-1];
}
}
}
void work()
{
int ans = 1;
int len = strlen(str);
for(int i=1;i<len;i++) if(str[i]<=str[i-1])
{
puts("0");
return;
}
for(int i=1;i<len;i++)
ans += C[26][i];
char ch='a';
for(int i=0;i<len;i++)
{
for(;ch<str[i];ch++)
{
ans+=C['z'-ch][len-i-1];
}
ch++;
}
printf("%d\n", ans);
}
int main()
{
init();
while(~scanf("%s", str))
work();
}