UVa129 -KryptonFactor
题意:一个字符串,若包含两个连续的相同子串,则为容易的串,如“ABCDBCDE”,否则称为困难的串,给定n和L,输出由前L个大写字母组成的字典序第n小的困难的串。
分析:这种题目只能枚举,但是如果只是简单的枚举,那么必定会超时,利用回溯就可以解决了。回溯高效的原因就在生成和检查过程有机结合起来,从而减少不必要的枚举。
每个位置的字母都从1到n枚举,枚举过程中只需要判断加入的字母会不会产生重复的连续串(因为之前的必定不会重复),不产生的话证明这是符合要求的困难的串,那么只需要搜索到第n个就行了,因为是字典序,所以后面的串总是以前面的串为前缀生成的,所以一直递归就行了。
借用紫书上面的话说:如果能把能把待求解的问题分解为不太多的步骤,每次又有不太多的选择,那么便可以考虑回溯了,回溯法的应用中需要注意避免不必要的判断,这题便是一个直接的体现。
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#define LL long long
#define INF 0x3f3f3f3f
#define N 1010
using namespace std;
int n, l, tag, cnt;
char ans[100000];
int check(char *s, int len)
{
int x = len/2;
for (int i = 1; i <= x; i++){
int flag = 1;
for (int j = len-1, tot = 0; tot < i && flag; j--, tot++)
if (s[j] != s[j-i]) flag = 0;
if (flag) return 0;
}
return 1;
}
void dfs(int len)
{
if (cnt++ == n){
int x = 0, k = 0;
for (int i = 0; i < len; i++){
if (++k <= 4) putchar(ans[i]);
if (k == 4){
k = 0;
if (++x == 16 && i != len-1) putchar('\n'), x = 0;
else{
if (i != len-1) putchar(' ');
}
}
}
printf("\n%d\n", len);
tag = 0;
}
if (tag){
for (int i = 0; i < l && tag; i++){
ans[len] = i+'A';
if (check(ans, len+1)) dfs(len+1);
else ans[len] = 0;
}
}
}
int main()
{
while (scanf("%d %d", &n, &l), n || l) cnt = 0, tag = 1, dfs(0);
return 0;
}