HDU 1867 A + B for you again 数据结构+KMP简单应用

A + B for you again 数据结构+KMP简单应用
Time Limit:1000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u

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 sdfg asdf ghjk
 

Sample Output

  
  
asdfg asdfghjk 解题思路: 看懂这题的题意,看到了复杂度之后,首先确定不能用普通的暴力算法来做 主要的目标还是求出他们结合的位数,因为这两个串先后顺序不确定,那么就要两个都求出来,然后找一个最优的 怎么求出来结合的位数? 假如结合的是A,B串,那我就把B当作模式串,A当作待匹配的串 那么我就让B去匹配A,当A匹配到最后一个的时候,然后获得此时的模式串下标,该下标就是结合的位数。
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 100005 ;
char text[maxn] ;
char str[maxn] ;
int f[maxn] ;
char ans1[2*maxn] ;
char ans2[2*maxn] ;
int find(char *T,char *P){
    int ans = 0 ;
    int n = strlen(T);
    int m = strlen(P);
    int j = 0 ;
    for(int i=0;i<n;i++){
        while(j&&P[j]!=T[i])j=f[j] ;
        if(P[j]==T[i])j++ ;
        if(i==n-1){
            return j;
        }
    }


    return ans ;
}
void getfail(char *P){
    int n = strlen(P) ;
    f[0] = 0 ;
    f[1] = 0 ;
    for(int i=1;i<n;i++){
        int j = f[i] ;
        while(j&&P[i]!=P[j])j=f[j] ;
        f[i+1] = (P[i]==P[j]?j+1:0) ;
    }
    return ;
}
int main(){
    while(~scanf("%s%s",text,str)){
        memset(f,0,sizeof(f));
        getfail(str) ;
        int k = find(text,str) ;
        //printf("k = %d\n",k);
        strcpy(ans1,text) ;
        strcat(ans1,str+k) ;
        //printf("%s\n",ans1);

        memset(f,0,sizeof(f));
        getfail(text) ;
        k = find(str,text) ;
        strcpy(ans2,str) ;
        strcat(ans2,text+k) ;
        //printf("%s\n",ans2);

        if(strlen(ans1)==strlen(ans2)){
            strcmp(ans1,ans2)<0?puts(ans1):puts(ans2) ;
        }else{
            strlen(ans1)>strlen(ans2)?puts(ans2):puts(ans1) ;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值