hdu 2203 亲和串

这题大概是数据比较水吧,我本以为会wa或者什么的,没想到直接亮了。讨论版里面神代码多的是,但是我也想把我的代码贴出来:

ac代码:

View Code
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

const int maxn=100000+5;

char s1[maxn],s2[maxn];
int len1,len2,next[maxn];

void get_next()
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<len2)
    {
        if(j==-1||s2[i]==s2[j])
            i++,j++,next[i]=j;
        else
            j=next[j];
    }
}

bool KMP()
{
    int i=0,j=0,sum=0;
    while(j<len2&&sum<len1)
    {

        if(j==-1||s1[i%len1]==s2[j])
        {
            if(j==-1)
                sum++;
            i++,j++;
        }
        else
            j=next[j];
    }
    if(j==len2)
        return true;
    else
        return false;
}

int main()
{
    while(~scanf("%s %s",s1,s2))
    {
        len1=strlen(s1);
        len2=strlen(s2);
        if(len1<len2)
        {
            printf("no\n");
            continue;
        }
        else
        {
            get_next();
            if(KMP())
                printf("yes\n");
            else
                printf("no\n");
        }
    }
    return 0;
}
勸君惜取少年時&莫待無花空折枝
原文地址:https://www.cnblogs.com/RainingDays/p/2766518.html