kmp(2)

来源:互联网 发布:钢筋工程量计算软件 编辑:程序博客网 时间:2024/04/30 21:25

A + B for you again

Time Limit : 5000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 6   Accepted Submission(s) : 2
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
 

Author
Wang Ye
 

Source
2008杭电集训队选拔赛——热身赛
题意:将两个字符串中相同部分去除,前一个串的后半部分与后一个字符串的前半部分匹配。给出两个串,问最短的串是什么。首先保证的是最短,然后保证按照字典序。
思路:kmp。由于不知道哪一个匹配另一个的字符多,所以要两个都匹配然后判断,相同时在按照字典序输出。
#include<iostream>#include<stdio.h>#include<string.h>#include<memory.h>using namespace std;char a[100005],b[100005];int next[100005];void getNext(char *b,int m){    memset(next,0,sizeof(next));    for(int i=1; i<m; i++)    {        int tmp=next[i-1];        while(tmp&&b[tmp]!=b[i])            tmp=next[tmp-1];        if(b[tmp]==b[i])            next[i]=tmp+1;        else            next[i]=0;    }}int kmp(char *a,char *b,int n){    int j=0,max=-1;    for(int i=0; i<n; i++)    {        while(j>0&&a[i]!=b[j])            j=next[j-1];        if(a[i]==b[j])            j++;        else            j=0;        //if(max<j)max=j;//j表示的是到i位置已经匹配的个数    }    return j;}int main(){    int t,m,n;    while(scanf("%s %s",&a,&b)!=EOF)    {        n=strlen(a);        m=strlen(b);        getNext(b,m);        int j=kmp(a,b,n);        getNext(a,n);        int l=kmp(b,a,m);        if(j==l)        {            if(strcmp(a,b)<=0)            {                for(int i=0; i<n; i++)                    printf("%c",a[i]);                for(int i=j; i<m; i++)                    printf("%c",b[i]);                printf("\n");            }            else            {                for(int i=0; i<m; i++)                    printf("%c",b[i]);                for(int i=l; i<n; i++)                    printf("%c",a[i]);                printf("\n");            }        }        else if(j>l)        {            for(int i=0; i<n; i++)                printf("%c",a[i]);            for(int i=j; i<m; i++)                printf("%c",b[i]);            printf("\n");        }        else        {            for(int i=0; i<m; i++)                printf("%c",b[i]);            for(int i=l; i<n; i++)                printf("%c",a[i]);            printf("\n");        }    }    return 0;}/*asdf sdfgasdf ghjk*/

原创粉丝点击