给出N(n<=9)个数字,每个数字最多6位,每位数都是1~4
将数字按照合并首尾重合的部分尽可能拼接,如:
123 + 234 -> 1234
如果有多种重合的长度,都可以考虑,如:
2433 + 3321 -> 243321,或者2433321
求最终能够拼接出的最长长度,如果都没有重合的部分,输出最长的字符串,只有两个有重合才能拼接?
4
3
123
141
234
2
24
123
4
343
2433
2213
3333
8
434121
441
4234
223142
23413
14342
224
234
6
3
9
24
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int T, N, answer, size[9];
char numbers[9][6], merged[50];
bool flag[9];
int getSize(char characters[]){ //计算这个数的长度(有几位)
for (int i = 0; i < 50; i++){
if (characters[i] == '\0'){
return i;
}
}
return -1;
}
//检查当前数字编号为current的数字跟前一个重合的长度
int checkOverlap(int current){
int mergedSize = getSize(merged); //计算一遍merged的长度
if (mergedSize == 0){ //如果merged的长度是0,那么说明肯定重合长度是0
return 0;
}
//从1遍历到当前的长度,size函数和length函数的作用一样,都是求字符串的长度
for (int overlapSize = 1; overlapSize < size[current]; overlapSize++){
bool findResult = true; //找到结果是true
for (int i = 0; i < overlapSize; i++){ //
int indexInMerged = mergedSize - overlapSize + i;
if (merged[indexInMerged] != numbers[current][i]){
findResult = false;
break;
}
}
if (findResult){
return overlapSize;
}
}
return -1;
}
//递归的DFS
void dfs(int finished){
int mergedSize = getSize(merged); //每次计算一遍已有的merged的长度
bool findNext = false;
for (int next = 0; next < N; next++){ //每个数字遍历一遍啊
if (!flag[next]){ //如果这个数字没有遍历过,
int overlapSize = checkOverlap(next);
if (overlapSize != -1){
findNext = true;
flag[next] = true;
for (int i = overlapSize; i < size[next]; i++){
merged[mergedSize - overlapSize + i] = numbers[next][i];
}
dfs(finished + 1);
flag[next] = false;
// 不可以只复原第一个位置
for (int i = overlapSize; i < size[next]; i++){
merged[mergedSize - overlapSize + i] = '\0';
}
}
}
}
if (!findNext){
if (answer < mergedSize){
answer = mergedSize;
}
}
}
int main(int argc, char** argv) {
freopen("sample_input.txt", "r", stdin);
setbuf(stdout, NULL);
scanf("%d", &T);
for (int test_case = 1; test_case <= T; ++test_case){ //遍历每个case
scanf("%d", &N); //有N个数字
for (int i = 0; i < N; i++){
scanf("%s", &numbers[i]); //numbers数组存放这N个数字
size[i] = getSize(numbers[i]); //size数组存放N个数字的长度
flag[i] = false; //最开始都没被遍历过
}
for (int i = 0; i < 50; i++){ //合并后的数字放在merged数组里面,初始化
merged[i] = '\0';
}
answer = 0; //初始化
dfs(0);
printf("%d\n", answer);
}
return 0;
}