如果一个字符串包含两个相邻的重复字串,则称他为 容易的串,其他串,称为困难的串
典型的,例如 BB,ABCDACABCAB 都是容易的串
相反的,例如 B CBABCBA 都是困难的串
输入正整数n和L 输入由前L个字符组成的, 前L个字符指在A - Z 中的前L个字符,L不会超过26, 字典序第n的困难的串,其实按递归顺序来,第n个就是字典序第n的困难的串
样例输入
7 3
30 3
样例输出
ABAC ABA
ABAC ABCA CBAB CABA CABC ACBA CABA
注意输出格式,具体参考代码或 Udebug
这题也是搜索与回溯的题,与其说搜索与回溯,不如说趁早剪枝。
能到达if语句的除了第一句就只有符合条件的语句了。
#include<bits/stdc++.h>
#define LL long long
using namespace std;
int n, L;
int cnt;
bool dfs(int cur, int* A) {
if(cnt++ == n) {
for(int i = 0; i < cur; i++) {
if(i == 64) cout << endl;
if(i && i % 4 == 0 && i != 64) cout << " ";
cout << char(A[i] + 'A');
}
cout << endl;
cout << cur << endl;
return 0;
}
for(int i = 0; i < L; i++) {
A[cur] = i;
bool ok = true;
for(int j = 1; j * 2 <= cur + 1; j++) { //这是一个通用的后n个和次后n个一个比较方法。
bool equal = true;
for(int k = 0; k < j; k++) {
if(A[cur - k] != A[cur - k - j]) {
equal = false;
break;
}
}
if(equal){
ok = false;
break;
}
}
if(ok) if(!dfs(cur + 1, A)) return 0;
}
return 1;
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0);
while(cin >> n >> L && n) {
cnt = 0;
int A[100];
dfs(0, A);
}
return 0;
}