POJ - 3080 Blue Jeans(暴力kmp)

题目链接

http://poj.org/problem?id=3080

题意

给你很多字符串,求出最长的相同子串。

思路

暴力找出第一个字符串的每一个子串,然后对剩余的每个字符串kmp一遍,看看是不是存在第一个字符串的子串,找出最长的那个就好了。

代码

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<map>
#include<algorithm>
#include<string>
#include<string.h>
#include<set>
#include<queue>
#include<stack>
#include<functional>
using std::pair;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<PII,int> PPI;
typedef pair<ll,int> PLI;
const double PI=acos(-1);
const int maxn = 2e5+10;
const int maxm = 1e6 + 10;
const int mod = 1e4+7;
const int INF = 0x3f3f3f3f;
using namespace std;
int nex[maxn];
void getNext(string t)
{
    nex[0]=-1;
    int j=0,k=-1;
    int len=t.length();
    while(j<len)
    {
        if(k==-1||t[j]==t[k]) nex[++j]=++k;
        else k=nex[k];
    }
}
int kmp(string s,string t)
{
    int i=0,j=0;
    int lens=s.length(),lent=t.length();
    while(i<lens&&j<lent)
    {
        if(j==-1||s[i]==t[j]) i++,j++;
        else j=nex[j];
        if(j==lent) return i-j+1;
    }
    return -1;
}
int main()
{
   int tt;
   cin>>tt;
   string s[15];
   while(tt--)
   {
       int n;
       scanf("%d",&n);
       for(int i=0;i<n;i++) cin>>s[i];
       string t;
       string res;
       int ma=0;
       for(int i=0;i<60;i++)
       {
           for(int j=i+1;j<=60;j++)
           {
               t=string(s[0].begin()+i,s[0].begin()+j);
               getNext(t);
               int f=0;
               for(int k=1;k<n;k++)
               {
                   if(kmp(s[k],t)==-1)
                   {
                       f=1;
                       break;
                   }
               }
               if(!f)
               {
                   if(ma<=j-i)
                   {
                       if(ma<j-i) res=t;
                       else res=min(res,t);
                       ma=j-i;
                   }
               }
           }
       }
       //cout<<ma<<endl;
       if(ma<3) printf("no significant commonalities\n");
        else
       cout<<res<<endl;
   }
}

猜你喜欢

转载自blog.csdn.net/a670531899/article/details/81570063