题目链接:腾讯:编码
可以用搜索做,一共25个字母,才四层,也就是25^4,还不到40万。
然后把每个结点保存起来就好了。
题目是25个字母,不是26个字母,没好好读题,被腾讯坑了又。
#include<iostream>
#include<algorithm>
#include<map>
#include<cstring>
using namespace std;
char word[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char cod[15]; //用来存字符串
int stc=0,index_=0; //stc代表字符串长度,index_是对应的编码值
map<string,int> m;
int dfs(int ith);
int main()
{
dfs(0); //深搜
string s;
map<string,int> :: iterator it;
while(cin>>s)
{
it=m.find(s);
cout<<it->second<<endl;
}
return 0;
}
int dfs(int ith)
{
if(ith==4) return 0; //如果已经放好了四个字母就结束
for(int i=0;i<25;++i)
{
cod[stc]=word[i]; //把这个字母加到字符串cod后面
stc++; //字符串长度+1
cod[stc]='\0'; //给这个字符串结尾加个\0
m[cod]=index_++; //将这个字符串存到map里,同时标记下标值index
dfs(ith+1); //放下一个字母
stc--; //回溯的过程,只需要将字符串长度减1就好
}
return 0;
}