1. 程式人生 > >hdu 3336 Count the string(kmp)

hdu 3336 Count the string(kmp)

you con span har which content all name his

Problem Description It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
s: "abab"
The prefixes are: "a", "ab", "aba", "abab"
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6.
The answer may be very large, so output the answer mod 10007.

Input The first line is a single integer T, indicating the number of test cases.
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters.

Output For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.

Sample Input 1 4 abab Sample Output 6

題意:給你一個字符串 問你 他的所有前綴 在當前字符串出現的總次數

思路:本來是想 每個前綴都去匹配一次 當然會TLE 所以仔細想想 next數組 不就是前綴數組的匹配情況嗎

所以 只要next數組>0我們就可以在總數上+1再加上非真前綴數即可

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define ll long long int
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1};
int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1};
const int inf=0x3f3f3f3f;
const ll mod=10007;
int nextt[200007];
int n;
void getnext(string s){
    nextt[1]=0;
    for(int i=2,j=0;i<=n;i++){
        while(j>0&&s[i-1]!=s[j]) j=nextt[j];
        if(s[i-1]==s[j]) j++;
        nextt[i]=j;
    }
}
int main(){
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--){
        string s;
        cin>>n>>s;
        getnext(s);
        int ans=n; //非真前綴數 
        for(int i=1;i<=n;i++){
            ans=(ans+(nextt[i]==0?0:1))%mod; //如果沒有前後綴相同就不處理 
        }
        cout<<ans<<endl;
    }
    return 0;
}

hdu 3336 Count the string(kmp)