hdu1867 A + B for you again(kmp)

时间:2023-01-03 17:01:35

题目链接:点这里!!!!


题意:(简单易懂自己看)


题解:直接kmp,但是要注意在+号前面的字符串指针一定要指到最后!!!


代码:


#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<vector>
#include<bitset>
#include<set>
#include<queue>
#include<stack>
#include<map>
#include<cstdlib>
#include<cmath>
#define PI 2*asin(1.0)
#define LL long long
#define pb push_back
#define pa pair<int,int>
#define clr(a,b) memset(a,b,sizeof(a))
#define lson lr<<1,l,mid
#define rson lr<<1|1,mid+1,r
#define bug(x) printf("%d++++++++++++++++++++%d\n",x,x)
#define key_value ch[ch[root][1]][0]C:\Program Files\Git\bin
const int  MOD = 10007;
const int N = 1e5+15;
const int maxn = 1e4+1000;
const int letter = 130;
const int INF = 1e17;
const double pi=acos(-1.0);
const double eps=1e-8;
using namespace std;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
char a[N],b[N];
int f[N];
int lena,lenb;
void getfail(char *p,int *f,int n){
    f[0]=-1;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;
    }
}
int solve(char *s,char *p){ ///p->next  s+p
    int lenp=strlen(p),lens=strlen(s);
    getfail(p,f,lenp);
    int i=0,j=0;
    while(i<lenp&&j<lens){
        if(i==-1||p[i]==s[j])++i,++j;
        else i=f[i];
    }
    if(j==lens) return i;
    return 0;
}
int main(){
    while(scanf("%s%s",a,b)!=EOF){
        lena=strlen(a),lenb=strlen(b);
        ///a+b
        int x=solve(a,b);
        ///b+a
        int y=solve(b,a);
        if(x>y||(x==y&&strcmp(a,b)<0)){
            printf("%s",a);
            for(int i=x;i<lenb;i++) printf("%c",b[i]);
            printf("\n");
        }
        else {
            printf("%s",b);
            for(int i=y;i<lena;i++) printf("%c",a[i]);
            printf("\n");
        }
    }
    return 0;
}