把所有串全排列,每次排列按顺序从左到右将各串叠加起来,叠加过程遵循最短原则。
search(f, f+n, g, g+m);在f中查找g,返回第一个与g完全匹配的起始位置,若无法匹配则返回f+m。
copy(f,f+n,g);将f中的n个元素拷贝到g中。
View Code
#include#include #include #include #include using namespace std;#define maxn 10#define maxl 10int n;char word[maxn][maxl];int f[maxn];char ans[maxn * maxl];void input(){ scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%s", word[i]);}void add(char *a, char *b){ int len_a = strlen(a); int len_b = strlen(b); if (search(a, a + len_a, b, b + len_b) != a + len_a) return; for (int i = max(0, len_a - len_b); i <= len_a; i++) { bool ok = true; for (int j = 0; j < len_a - i; j++) if (a[i + j] != b[j]) { ok = false; break; } if (ok) { copy(b, b + len_b + 1, a + i); return; } }}int main(){ //freopen("t.txt", "r", stdin); input(); for (int i = 0; i < n; i++) f[i] = i; int len = maxn * maxl; do { ans[0] = 0; for (int i = 0; i < n ;i++) add(ans, word[f[i]]); len = min(len, (int)strlen(ans)); }while (next_permutation(f, f + n)); printf("%d\n", len); return 0;}