HDU 6629 string matching next数组的运用 2019 Multi-University Training Contest 5

string matching
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

题目大意:
说白了,就是让你按照它给出的伪代码,算出需要匹配比较多少次;

分析:
明白给出的伪代码之后,可以知道,这题如果不考虑时间复杂度的话,不就是求当前字符能匹配的最长前缀与最长后缀吗;但这样时间不允许;

这就需要用到KMP里面的next数组了(大家要先弄明白next数组的含义才行);
类似递推,大家看一下代码就差不多懂了

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<cmath>
#include<cstring>
#include<set>
#include<queue>
#include<stack>
#include<map>
#define rep(i,a,b) for(int i=a;i<=b;i++)
typedef long long ll;
using namespace std;
const int N=1e6+10;
const int INF=0x3f3f3f3f;
int Next[N];
char str[N];
int a[N];
void get_next(int len){
    Next[0]=-1;
    int j=-1;
    int i=0;
    while(i<len){
        if(j==-1 || str[i]==str[j]){
            i++;
            j++;
            Next[i]=j;
        }else
        j=Next[j];
    }
//    for(int i=0;i<len;i++)
//        cout<<Next[i]<<" ";
//    cout<<endl;
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    int T;
    scanf("%d\n",&T);
    while(T--){
        scanf("%s",str);
        int len=strlen(str);
        get_next(len);
        ll ans=0;
        for(int i=1;i<len;i++){
            a[i]=a[Next[i]]+1;
            ans+=a[i];
        }

        printf("%lld\n",ans);
    }
    return 0;
}


发布了229 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/c___c18/article/details/98502001