UVa 10602 - Editor Nottoobad

贪心,从第一个给定的字符串开始,每次都选取与前一个字符串的前缀最大匹配的字符串为下一个字符串,以此类推。

代码如下:

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值