题意:定义困难的串为字符串中存在相邻的相同的子串。现在用前L个大写字母来得到困难的串,求字典序第N个串是什么。
思路:因为要构造出字典序的第N个困难的串,同时大写字母还不给定,我们只能用搜索来完成这个问题了。
我们从前到后对每个位置,从大到小枚举每个字母,同时检查是否是困难的串。
而在检查是否是困难的串的问题上,我们这里利用的递推的思想,即考虑当前新加入的字符对整个字符串的影响,而前面字符已经在前面已经判断了。
经过测试发现,当L>=3的时候,就很少回溯了,这个时候就能构造无限长的串了。
注意:这个题还有坑就是在输出格式上,按照题目要求,每4个一组,当有16组时,我们还要换行输出。
代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAX = 1000;
int str[MAX];
int cnt,N,L;
bool judge(int idx)
{
for(int i = 1; 2 * i <= idx + 1; ++i){
bool eq = true;
for(int j = 0; j < i; ++j)
if(str[idx - j] != str[idx - j - i]){
eq = false;
break;
}
if(eq) return false;
}
return true;
}
bool dfs(int idx)
{
if(cnt++ == N){
// for(int i = 0; i < idx; ++i){
// if(i && i % 4 == 0 && i != 64) putchar(' ');
// if(i == 64) putchar('\n');
// putchar('A'+str[i]);
// }
// printf("\n%d\n",idx);
return true;
}
for(int i = 0; i < L; ++i){
str[idx] = i;
if(judge(idx) && dfs(idx+1)) return true;
}
return false;
}
int main(void)
{
freopen("input.txt","r",stdin);
while(scanf("%d%d",&N,&L),L||N){
cnt = 0;
dfs(0);
}
return 0;
}