贪心,从第一个给定的字符串开始,每次都选取与前一个字符串的前缀最大匹配的字符串为下一个字符串,以此类推。
代码如下:
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<ctime>
using namespace std;
struct group
{
char w[102];
int num;
};
int b_cmp(const void *a, const void *b) // 与第一个固定字符串有相同的前缀的所有字符串特殊排序处理
{
group *aa = (group*)a;
group *bb = (group*)b;
if(aa->num != bb->num)
return bb->num - aa->num;
return strcmp(aa->w, bb->w); // 公共前缀相同的,以其ascll码值排序
}
int c_cmp(const void *a, const void *b)
{
return strcmp((char*)a, (char*)b); // 剩下的字符串排序
}
struct group b[102];
int main()
{
#ifdef test
freopen("in.txt", "r", stdin);
#endif
int t, n;
char a[102], str[102], c[102][102];
scanf("%d", &t);
while(t--)
{
int count, bct = 0, cct = 0, k;
scanf("%d", &n);
scanf("%s", a);
count = strlen(a);
for(int i = 1; i < n; i++)
{
scanf("%s", str);
if(str[0] == a[0])
{
int knum = 1;
for(int j = 1; a[j]!='\0' && str[j]!='\0'; j++,knum++)
if(a[j] != str[j])
break;
strcpy(b[bct].w, str);
b[bct].num = knum;
bct++;
}
else
strcpy(c[cct++], str);
}
qsort(b, bct, sizeof(b[0]), b_cmp);
qsort(c, cct, sizeof(c[0]), c_cmp);
if(bct > 0)
{
count += strlen(b[0].w) - b[0].num;
for(int i = 1; i < bct; i++)
{
for(k = 0; b[i - 1].w[k] != '\0' && b[i].w[k] != '\0'; k++)
if(b[i - 1].w[k] != b[i].w[k])
break;
count += strlen(b[i].w) - k;
}
}
if(cct > 0)
{
count += strlen(c[0]);
for(int i = 1; i < cct; i++)
{
for(k = 0; c[i - 1][k] != '\0' && c[i][k] != '\0'; k++)
if(c[i - 1][k] != c[i][k])
break;
count += strlen(c[i]) - k;
}
}
printf("%d\n", count);
puts(a);
for(int i = 0; i < bct; i++)
puts(b[i].w);
for(int i = 0; i < cct; i++)
puts(c[i]);
}
return 0;
}