Count the string - HDU 3336(next+dp)

题目大意:给你一个串求出来这个串所有的前缀串并且与前缀串相等的数量,比如:
ababa 前缀串{"a", "ab", "aba", "abab", "ababa"};
每个前缀串出现的次数{3, 2, 2, 1, 1},那么结果就是 9。
 
分析:我们可以用dp[i],表示前i长度的串的结果,那么就可以得到下面的转移方程 dp[i] = dp[next[i]] + 1。
代码如下。
=============================================================================================
#include<stdio.h>
#include<string.h>

const int MAXN = 1e6+7;
const int oo = 1e9+7;
const int mod = 10007;

char s[MAXN];
int next[MAXN], dp[MAXN];

void GetNext(char s[], int N)
{
    int i=0, j=-1;
    next[0] = -1;

    while(i < N)
    {
        if(j==-1 || s[i]==s[j])
            next[++i] = ++j;
        else
            j = next[j];
    }
}

int main()
{
    int T, N, ans;

    scanf("%d", &T);

    while(T--)
    {
        scanf("%d%s", &N, s);

        GetNext(s, N);

        next[N+1] = -1;
        ans = dp[0] = 0;

        for(int i=1; i<=N; i++)
        {
            dp[i] = (dp[next[i]] + 1) % mod;
            ans = (ans+dp[i]) % mod;
        }

        printf("%d\n", ans);
    }

    return 0;
}

 

posted @ 2015-08-15 13:06  无忧望月  阅读(111)  评论(0编辑  收藏  举报
levels of contents