poj 3080 Blue Jeans(数据结构:KMP)

一道比较简单的字符串匹配题

因为数据比较多,所以要注意细节

题目的意思是找到给出的多个串中最长且字典序最小的公共子串

我的做法是把第一个字符串的所有子串求出来存在tmp字符串数组中

然后循环判断tmp中字符串是否与所有字符串有公共子串,有的话取最长且字典序最小的

刚开始给tmp排序了,排序的方法是按长度从小到大排列,长度相同的字符串按字典序从大到小排列

这样到这找,找到的第一个满足条件的tmp一定是最优的

但是超时了,估计排序过程写的太弱了

后来直接把tmp全部遍历一遍,取最优的

一定要注意初始化!


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAXN 62
#define LL long long
using namespace std;

int len[12], next[MAXN];
char chs[MAXN];
char str[12][MAXN];
char tmp[12000][MAXN];

void get_next(char p[]) {
    int len_p = strlen(p);
    int i = 0, j = -1;
    next[0] = -1;
    while(i < len_p) {
        if(j==-1 || p[i]==p[j]) {
            ++i, ++j;
            next[i] = j;
        } else j = next[j];
    }
}

bool kmp(char s[], char t[]) {
    int lens = strlen(s);
    int lent = strlen(t);
    int i = 0, j = 0;
    get_next(s);
    while(i < lent) {
        if(j==-1 || t[i]==s[j]) {
            ++i, ++j;
        } else j = next[j];
        if(j == lens)
            return true;
    }
    return false;
}


int main(void) {
    int n, m, cnt;
    scanf("%d", &n);
    while(n--) {
        scanf("%d", &m);
        for(int i=0; i<m; ++i) {
            scanf("%s", str[i]);
            len[i] = strlen(str[i]);
        }
        cnt = 0;
        for(int i=0; i<len[0]; ++i) {
            for(int j=3; i+j<=len[0]; ++j) {
                strncpy(tmp[cnt], str[0]+i, j);
                ++cnt;
            }
        }
/*
        for(int i=0; i<cnt; ++i) {
            for(int j=i+1; j<cnt; ++j) {
                if(strlen(tmp[i]) > strlen(tmp[j]) || (strlen(tmp[i])==strlen(tmp[j]) && strcmp(tmp[i], tmp[j]) < 0)) {
                    strcpy(chs, tmp[i]);
                    strcpy(tmp[i], tmp[j]);
                    strcpy(tmp[j], chs);
                }
            }
        }

        printf("cnt = %d\n", cnt);
        for(int i=0; i<cnt; ++i)
            printf("%s\n", tmp[i]);
*/
        int ans;
        memset(chs, 0, sizeof(chs));
        for(int i=cnt-1; i>=0; --i) {
            ans = 0;
            for(int j=0; j<m; ++j) {
                if(!kmp(tmp[i], str[j])) {
                    break;
                } else ans++;
            }
            if(ans == m && (strlen(tmp[i])>strlen(chs) || (strlen(tmp[i])==strlen(chs) && strcmp(tmp[i], chs)<0))) {
                strcpy(chs, tmp[i]);
            }
        }
        if(strlen(chs) >= 3)
            printf("%s\n", chs);
        else
            printf("no significant commonalities\n");
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值