首页 > ACM题库 > HDU-杭电 > HDU 3336-Count the string-动态规划-[解题报告]HOJ
2014
03-16

HDU 3336-Count the string-动态规划-[解题报告]HOJ

Count the string

问题描述 :

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.

输入:

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.

输出:

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.

样例输入:

1
4
abab

样例输出:

6

题目链接:hdu3336

假设两串字符完全相等,next[j]=i,代表s[1...i]==sum[j-i+1....j],这一段其实就是前缀

i~j之间已经不可能有以j结尾的子串是前缀了,不然next【j】就不是 i 了

设dp【i】:以string[i]结尾的子串总共含前缀的数量

所以dp[j]=dp[i]+1,即以i结尾的子串中含前缀的数量加上前j个字符这一前缀

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
using namespace std;
const int N = 200005;
char a[N];
int next[N],d[N];
void get_next(char *b)
{
    int i = -1, j = 0;
    next[0] = -1;
    int len = strlen(b);
    while(j < len)
    {
        if(i == -1 || b[i] == b[j])
            next[++j] = ++i;
        else
            i = next[i];
    }
}
int main()
{
    int T,i,n;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%s",&n,a);
        get_next(a);
        for(i = 1; i <= n; i ++)
            d[i] = 1;
        d[0] = 0;
        int sum = 0;
        for(i = 1; i <= n; i ++)
        {
            d[i] = d[next[i]] + 1;
            sum += d[i]%10007;
        }
        printf("%d\n",sum%10007);
    }
    return 0;
}

参考:http://blog.csdn.net/jzmzy/article/details/20143803


  1. 老实说,这种方法就是穷举,复杂度是2^n,之所以能够AC是应为题目的测试数据有问题,要么数据量很小,要么能够得到k == t,否则即使n = 30,也要很久才能得出结果,本人亲测

  2. bottes vernies blanches

    I appreciate the efforts you men and women place in to share blogs on such sort of matters, it was certainly useful. Keep Posting!

  3. #include <cstdio>

    int main() {
    //answer must be odd
    int n, u, d;
    while(scanf("%d%d%d",&n,&u,&d)==3 && n>0) {
    if(n<=u) { puts("1"); continue; }
    n-=u; u-=d; n+=u-1; n/=u;
    n<<=1, ++n;
    printf("%dn",n);
    }
    return 0;
    }