原题解题思路
已知字典序是字母的最小升序,所以可以直接根据字母的组合建一个类似于树的结构,然后进行bfs或者说是中序遍历计数即可。
细节问题
因为STL在这里用不了,所以我在使用的bfs的时候必须手搓一个队列。
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
char res[10];
const int N = 1e6 + 10;
struct node
{
char str[10];
int id;
};
node que[N];
int hh,tt;
void init()
{
hh = 0;
tt = 0;
}
bool que_empty() {return hh == tt;}
void que_pop() { hh++; }
void que_push(node x) { que[tt++] = x; }
node que_front() { return que[hh]; }
int bfs()
{
init();
int idx = 1;
node first;
first.id = 0;
strcpy(first.str, "");
que_push(first);
while (!que_empty())
{
node head = que_front(); que_pop();
if (strcmp(head.str, res) == 0) return head.id;
for (char a = 'a'; a <= 'z'; a++)
{
while (a <= head.str[strlen(head.str) - 1] && a <= 'z') a++;
if (a > 'z') break;
node tail;
memset(tail.str, '\0', sizeof tail.str);
strcpy(tail.str,head.str);
tail.str[strlen(tail.str)] = a;
tail.id = idx ++;
que_push(tail);
}
}
return -1;
}
int main()
{
int n;
scanf("%d", &n);
while (n--)
{
scanf("%s", res);
printf("%d\n", bfs());
}
return 0;
}