网址如下:
Krypton Factor - UVA 129 - Virtual Judge (vjudge.net)
(第三方网站)
一道枚举题,用回溯法枚举
因为添加新字符之前的字串已经判断过了,所以只需要判断包含新字符的字串是否有相邻的重复字串就可以了
代码如下:
#include<cstdio>
const int maxn = 81;
char A[maxn];
int cnt, n, L;
bool judge(int b, int e){
bool is_h = false;
for(int i = b, j = (b + e) / 2; j < e; i++, j++)
if(A[i] != A[j]){is_h = true; break;}
return is_h;
}
void print_ans(int cur){
if(cnt > n) return;
if(cnt == n){
for(int i = 0, j = 0, k = 0; i < cur; i++, j++){
if(j == 4){j = 0; if(++k == 16) putchar('\n'); else putchar(' ');}
printf("%c", A[i]);
}
putchar('\n');
printf("%d\n", cur);
cnt++;
}
else{
for(int i = 0; i < L; i++){
A[cur] = 'A' + i;
//判断是否为hard串
bool is_h = true;
for(int i = cur - 1; i >= 0; i -= 2)
if(!judge(i, cur + 1)){is_h = false; break;}
if(is_h){cnt++; print_ans(cur + 1);}
}
}
}
int main(void)
{
while(scanf("%d%d", &n, &L) == 2 && n){
cnt = 0;
print_ans(0);
}
return 0;
}