hdu1867 A + B for you again KMP

來源:互聯網
上載者:User

      題意:給你兩個串,求他們串連成的最短串,串連時合并相同部分。還有當以兩種方式串連(s1s2、s2s1)得到的最短長度相同時,取字典序最小那種。

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int N=100005;int next[N];void init(char *s)//get next[]{    int i,j;    next[0]=0;    for(i=1,j=0;s[i];i++)    {        while(j>0&&s[j]!=s[i])            j=next[j-1];        if(s[j]==s[i])            j++;        next[i]=j;    }}int getLength(char *s1,char *s2)//get the length of the same part{    int i,j;    init(s2);    for(i=j=0;;i++)    {        while(j>0&&s1[i]!=s2[j])            j=next[j-1];        if(s1[i]==s2[j])            j++;        if(s1[i+1]=='\0')            break;        if(s2[j]=='\0')            j=0;    }    return j;}void output(char *s1,char *s2,int n){    int len=strlen(s1);    for(int i=0;i<len-n;i++)        putchar(s1[i]);    printf("%s\n",s2);}int main(){    char s1[N],s2[N];    while(~scanf("%s%s",s1,s2))    {        int len1=getLength(s1,s2);        int len2=getLength(s2,s1);        if(len1>len2)            output(s1,s2,len1);        else if(len2>len1)            output(s2,s1,len2);        else        {            if(strcmp(s1,s2)<0)                output(s1,s2,len1);            else                output(s2,s1,len2);        }    }    return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.