hdoj 1867 A + B for you again【kmp,前缀与后缀的匹配】

来源:互联网 发布:ppt柱状图显示数据 编辑:程序博客网 时间:2024/04/29 04:10

A + B for you again

Problem Description
Generally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf” and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.
 

Input
For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 10^5 and won’t be empty.
 

Output
Print the ultimate string by the book.
 

Sample Input
asdf sdfgasdf ghjk
 

Sample Output
asdfgasdfghjk
 

题目大意:输入两个字符串啊a和b,然后把两个字符串收尾相连,相连时候,把a的后缀和b的前缀重合【b的后缀和a的前缀重合】,还要求输出的合并字符串字典序最小且长度最短。

思路:首先比较两个字符串的长度,若一样长,则比较两个字符串的字典序,字典序小的放前面,

        然后再计算a的后缀和b的前缀的匹配长度len1,接着计算b的后缀和a的前缀的匹配长度len2,如果len1<len2,则b在前,a在后;否则,a在前,b在后。

Accept代码【C++】【46MS】【2300K】

#include <cstdio>#include <cstring>using namespace std;char str_1[100001], str_2[100001];int p[100001];int total;void Kmp_huan(char *k, int len) {    int i = 0, j = -1;    p[0] = -1;    while(i + 1 < len) {        if(j == -1 || k[i] == k[j]) {        i++, j++;        if(k[i] == k[j])        p[i] = p[j];        else        p[i] = j;//优化,即数据结构书中求的nextval数组【http://blog.csdn.net/nailnehc/article/details/49184599】}        else            j = p[j];    }}int KMP(char *s, char *t, int len_s, int len_t) {    int i = 0, j = 0;    memset(p, 0, sizeof(p));    Kmp_huan(t, len_t);    while(i < len_s){         while(s[i] != t[j]) {        if(p[j] == -1) {        j = 0;        break;}j = p[j];}if(s[i] == t[j])j++;i++;    }return j;}int main() {    int x = 0, y = 0;    int len_1, len_2;    while(~scanf("%s %s", str_1, str_2)) {//笔者在这里吃了瘪,注意哈<---------  看过来 本来是【while(1) {   scanf()...   }】Output Limit Exceeded        len_1 = strlen(str_1);        len_2 = strlen(str_2);        x = KMP(str_1, str_2, len_1, len_2);        y = KMP(str_2, str_1, len_2, len_1);        if(x == y) {            if(strcmp(str_1, str_2) > 0) {                printf("%s", str_2);                printf("%s\n", str_1 + y);            }            else {                printf("%s", str_1);                printf("%s\n", str_2 + y);            }        }        else if(x > y){            printf("%s", str_1);            printf("%s\n", str_2 + x);        }        else {            printf("%s", str_2);            printf("%s\n", str_1 + y);        }    }    return 0;}


0 0
原创粉丝点击