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 ve 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 ve 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 ve letters. Only the lower case alphabetic {a,b,…,z} characters will be used as input. The rst letter of a word will appear as the rst character on an input line.
The input will be terminated by end-of- le.
Output
The output is a single integer, greater than or equal to zero (0) and less than or equal 83681. The rst digit of an output value should be the rst 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
题意:
字符a对应1,依次往后加1,直到最大的五位字符vwxyz,对应83681
输入其中
思路:
用map储存每个字符串对应的值
#include<iostream>
#include<queue>
#include<map>
#include<string>
using namespace std;
map<string,int> words;//储存每个字符串对应的值
queue<string> que;//声明一个队列
void initial()//初始化
{
string str,s;
int count=1;
for(char ch='a';ch<='z';ch++)//先储存26个字母
{
str=ch;
words[str]=count++;
que.push(str);
}
while(!que.empty())//bfs
{
str=que.front();
que.pop();
if(str.length()<5)//长度小于5
{
for(char ch=(*str.rbegin())+1;ch<='z';ch++)
{
s=str+ch;//每个字母派生一系列字符串
words[s]=count++;//每次值加1
que.push(s);//添加到队列中
}
}
}
}
int main()
{
string str;
initial();
map <string,int>::iterator it;//声明一个map类型的迭代器
while(cin>>str)
{
it=words.find(str);//找到该字符在map中的位置
if(it!=words.end())
cout<<it->second<<endl;
else
cout<<0<<endl;
}
return 0;
}