hdu1238 kmp

Posted walfy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu1238 kmp相关的知识,希望对你有一定的参考价值。

You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings. 

InputThe first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string. 
OutputThere should be one line per test case containing the length of the largest string found. 
Sample Input

2
3
ABCD
BCDFF
BRCD
2
rose
orchid

Sample Output

2
2
题意:找n个字符串里的公共子串,相反方向的也算公共子串
题解:枚举第一个的子串和后面的进行kmp
(1a的感觉真tm爽)
技术分享
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define ll long long
#define mod 10007
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1

using namespace std;

const double g=10.0,eps=1e-9;
const int N=100+5,maxn=(1<<18)-1,inf=0x3f3f3f3f;

int Next[N],slen,plen;
string a[N],ptr,str;

void getnext()
{
    int k=-1;
    Next[0]=-1;
    for(int i=1;i<slen;i++)
    {
        while(k>-1&&str[k+1]!=str[i])k=Next[k];
        if(str[k+1]==str[i])k++;
        Next[i]=k;
    }
}
bool kmp()
{
    int k=-1;
    for(int i=0;i<plen;i++)
    {
        while(k>-1&&str[k+1]!=ptr[i])k=Next[k];
        if(str[k+1]==ptr[i])k++;
        if(k==slen-1)return 1;
    }
    return 0;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
 //   cout<<setiosflags(ios::fixed)<<setprecision(2);
    int t,n;
    cin>>t;
    while(t--){
        cin>>n;
        for(int i=0;i<n;i++)cin>>a[i];
        int ans=0;
        for(int i=1;i<=a[0].size();i++)
        {
            for(int j=0;j<=a[0].size()-i;j++)
            {
                str=a[0].substr(j,i);
                slen=str.size();
                getnext();
                bool flag=1;
                for(int k=1;k<n;k++)
                {
                    ptr=a[k];
                    plen=a[k].size();
                    if(kmp())continue;
                    reverse(ptr.begin(),ptr.end());
                    if(kmp())continue;
                    flag=0;
                    break;
                }
                if(flag)ans=max(ans,slen);
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
View Code

 






以上是关于hdu1238 kmp的主要内容,如果未能解决你的问题,请参考以下文章

hdu1238 kmp

hdu1238 Substrings 扩展KMP

kuangbin专题十六 KMP&&扩展KMP HDU1238 Substrings

hdu-2328(暴力枚举+kmp)

HDU 1238 Substrings (水)

hdu 1238 字符串处理 暴力