原题链接:https://vjudge.net/problem/UVA-129
分类:回溯法
备注:隐性回溯,字符串
代码如下:
#include<cstdio>
using namespace std;
const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n, L, cnt;
char ans[90];
bool over;
bool check(int pos) {
int len = 1, tot = pos + 1;
while (2 * len <= tot) {
int last = pos - len;
bool flag = true;
for (int i = pos; i > last; i--) {
if (ans[i] != ans[i - len]) {
flag = false;
break;
}
}
if (flag)return false;
len++;
}
return true;
}
void solve(int pos) {//在下标为pos处添加字符
if (over)return;
if (cnt == n) {
for (int i = 0, num = 0; i < pos; i++) {
printf("%c", ans[i]);
if ((i + 1) % 4 == 0 && i + 1 != pos) {
num++;
if (num % 16 == 0)
printf("\n");
else
printf(" ");
}
}
printf("\n%d\n", pos);
over = true;
return;
}
for (int i = 0; i < L; i++) {
ans[pos] = a[i];
if (check(pos)) {
cnt++;
solve(pos + 1);
if (over)return;
}
}
}
int main(void) {
while (scanf("%d %d", &n, &L) == 2 && L) {
over = false;
cnt = 0;
solve(0);
}
return 0;
}