HDU 5510 Bazinga

2015 ACM / ICPC 沈阳站 B题

暴力+KMP

无法理解为什么能AC,极限数据应该会超时的吧...

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;

const int maxn=2005;
int tCase,n;
char S[maxn],T[maxn];
int Next[maxn];
int slen,tlen;
bool flag[maxn];
char s[505][maxn];

void getNext()
{
    int j, k;
    j = 0; k = -1; Next[0] = -1;
    while(j < tlen)
        if(k == -1 || T[j] == T[k])
            Next[++j] = ++k;
        else
            k = Next[k];

}
/*
返回模式串T在主串S中首次出现的位置
返回的位置是从0开始的。
*/
int KMP_Index()
{
    int i = 0, j = 0;
    getNext();

    while(i < slen && j < tlen)
    {
        if(j == -1 || S[i] == T[j])
        {
            i++; j++;
        }
        else
            j = Next[j];
    }
    if(j == tlen)
        return i - tlen;
    else
        return -1;
}

int main()
{
    scanf("%d",&tCase);
    for(int Case=1;Case<=tCase;Case++)
    {
        scanf("%d",&n);
        memset(flag,0,sizeof flag);
        int ans=-1;
        for(int i=0;i<n;i++)
        {
            scanf("%s",s[i]);
            for(int j=0;j<=i-1;j++)
            {
                if(flag[j]) continue;
                strcpy(T,s[j]);
                strcpy(S,s[i]);
                slen=strlen(S);
                tlen=strlen(T);

                if(KMP_Index()!=-1) flag[j]=1;
                else ans=i;
            }
        }
        printf("Case #%d: ",Case);
        if(ans!=-1) ans++;
        printf("%d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/4939475.html