UVA129-困难的串-Krypton Factor

题意

让你用前L个字母来构造出字典序为n的字符串,要求这个字符串满足:字符串中不包含两个相邻的重复子串。

思路

思路非常简单,利用DFS来枚举串,如果枚举出来的串符合要求就继续向下递归,否则回溯。这里比较麻烦的是判断字符串中到底存不存在相邻的重复子串,这里lrj给出了比较好的思路,非常值得借鉴:因为在之前找到的字符串中一定不存在相邻的重复子串,因此新得到的字符串唯一可能存在相邻的重复子串的地方就是新添加的字符所在的子串中,因此只需要枚举字符串的后缀,看后缀中是否存在相邻的重复子串即可。

代码

代码未AC,仅供参考

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 100;

int n, l, tot, s[N];

int dfs(int cur) {
    if (tot++ == n) {
        for (int i = 0; i < cur; i++) {
            if (i && i % 4 == 0) printf(" ");
            printf("%c", s[i] + 'A');
        }
        printf("\n%d\n", cur);
        return 1;
    }
    for (int i = 0; i < l; i++) {
        s[cur] = i;
        bool flag = true;
        for (int j = 1; j * 2 <= cur + 1; j++) {
            bool equal = true;
            for (int k = 0; k < j; k++) {
                if (s[cur - k] != s[cur - j - k]) { equal = false; break; }
            }
            if (equal) { flag = false; break; }
        }
        if (flag) {
            if (dfs(cur + 1)) return 1;
        }
    }
    return 0;
}

void solve() {
    while (cin >> n >> l && n && l) {
        tot = 0;
        dfs(0);
    }
}

int main() {
    solve();
    return 0;
}
posted @ 2021-10-01 18:32  牟翔宇  阅读(7)  评论(0编辑  收藏  举报