2019 Multi-University Training Contest 5

String matching is a common type of problem in computer science. One string matching problem is as following:

Given a string s[0…len−1] , please calculate the length of the longest common prefix of s[i…len−1] and s[0…len−1] for each i>0 .

I believe everyone can do it by brute force.
The pseudo code of the brute force approach is as the following:
 

 



We are wondering, for any given string, what is the number of compare operations invoked if we use the above algorithm. Please tell us the answer before we attempt to run this algorithm.

 

 

Input

The first line contains an integer T , denoting the number of test cases.
Each test case contains one string in a line consisting of printable ASCII characters except space.

* 1≤T≤30

* string length ≤106 for every string

 

 

Output

For each test, print an integer in one line indicating the number of compare operations invoked if we run the algorithm in the statement against the input string.

 

 

Sample Input

 

3 _Happy_New_Year_ ywwyww zjczzzjczjczzzjc

 

 

Sample Output

 

17 7 32

 

#include <iostream> 
#include <cstdio> 
#include <fstream> 
#include <algorithm> 
#include <cmath> 
#include <deque> 
#include <vector> 
#include <queue> 
#include <string> 
#include <cstring> 
#include <map> 
#include <stack> 
#include <set> 
using namespace std;  
char x[1000001];
long long Next[1000001],ex[1000001];
void getNext(char *str)
{
    int i=0,j,po,len=strlen(str);
    Next[0]=len;
    while(str[i]==str[i+1]&&i+1<len)
    i++;
    Next[1]=i;
    po=1;
    for(i=2;i<len;i++)
    {
        if(Next[i-po]+i<Next[po]+po)
            Next[i]=Next[i-po];
        else
        {
            j=Next[po]+po-i;
            if(j<0)j=0;
            while(i+j<len&&str[j]==str[j+i])
            j++;
            Next[i]=j;
            po=i;
        }
    }
}
void getkmp(char *s1,char *s2)
{
    int i=0,j,po,len=strlen(s1),l2=strlen(s2);
    getNext(s2);
    while(s1[i]==s2[i]&&i<l2&&i<len)
    i++;
    ex[0]=i;
    po=0;
    for(i=1; i<len; i++)
    {
        if(Next[i-po]+i<ex[po]+po)
        ex[i]=Next[i-po];
        else
        {
            j=ex[po]+po-i;
            if(j<0)j=0;
            while(i+j<len&&j<l2&&s1[j+i]==s2[j])
            j++;
            ex[i]=j;
            po=i;
        }
    }
}
int main()
{
    long long int i,t,n,s;
    scanf("%lld\n",&t);
    while(t--)
    {
        memset(ex,0,sizeof(ex));
        s=0;
        scanf("%s",x);
        n=strlen(x);
        getkmp(x,x);
        for( i=1;i<=n-1;i++)
        {
            if(ex[i]==0)
            s++;
            else
            s+=ex[i]+1;
            if(ex[i]+i>=n)
            s--;
        }
        printf("%lld\n",s);
    }

}

 

全部评论

相关推荐

02-28 13:25
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
zzzilik:没事的,才刚刚开始,后面会捞的,这个三天没人发起面试自动结束,但是面试官还是能看到简历,四月份主战场会慢慢捞
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务