字典序--Educoder(算法设计书上原题--暴力)

原题解题思路

已知字典序是字母的最小升序,所以可以直接根据字母的组合建一个类似于树的结构,然后进行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();
		//printf("%d\t%s\n", idx,head.str);
		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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值