HDU 3336 Count the string

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baodream/article/details/79951135

题目链接:http://hdu.hustoj.com/showproblem.php?pid=3336

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
14abab
 

Sample Output
6


题目描述:求字符串的出现的所有前缀次数和

思路:DP+KMP。当某一个字母新出现时,其对应Next数组回溯到-1的位置回溯了多少次就是对ans贡献+多少次(Next数组特性得到的),又next数组每次回溯的次数一样,所以不用每次都找,用DP数组记录一下就ok。


代码:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<map>

using namespace std;

#define FOU(i,x,y) for(int i=x;i<=y;i++)
#define FOD(i,x,y) for(int i=x;i>=y;i--)
#define MEM(a,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)

const double EXP = 1e-9;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const ll MINF = 0x3f3f3f3f3f3f3f3f;
const int mod = 10007;
const int N = 1e6+5;

string str,mo;
int Next[200005];
int dp[200005];

void Get_next()
{
    int i,j;
    j = Next[0] = -1;
    i = 0;
    int len = str.length();
    while(i<len)
    {
        while(j!=-1&&str[i]!=str[j])
            j = Next[j];
        Next[++i] = ++j;
    }
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    std::ios::sync_with_stdio(false);
    int t,n;
    cin>>t;
    while(t--)
    {
        cin>>n;
        cin>>str;
        mo="";
        Get_next();
        MEM(dp,0);
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            dp[i] = (dp[Next[i]]+1)%mod;
            ans = (ans+dp[i])%mod;
        }
        cout<<ans<<endl;
    }
    return 0;
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页