HDU

来源:互联网 发布:知乎可以邮箱注册吗 编辑:程序博客网 时间:2024/05/23 20:24

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3336

题意:求这个字符串每个前缀在字符串中出现了多少次。

思路:dp[i]记录在长度为i的前缀时有多少个,递推为dp[i]=dp[Next[i]]+1,+1是因为长度为i的前缀第一次出现肯定要多一个,Next[i]表示i的前后缀匹配的长度,dp[Next[i]]表示已经出现的前缀又增加了相同的。具体看代码。


代码:

#include <cstdio>#include <cmath>#include <iostream>#include <cstring>#include <algorithm>#include <queue>#include <stack>#include <vector>#include <map>#include <numeric>#include <set>#include <string>#include <cctype>#include <sstream>#define INF 0x3f3f3f3fusing namespace std;typedef long long LL;typedef pair<int, int> P;const int maxn = 20000 + 5;const int mod = 10007;//freopen ("in.txt", "r", stdin);const int N = 200005;int Next[N];char S[N], T[N];int slen, tlen;void getNext() {    int j, k;    j = 0;    k = -1;    Next[0] = -1;    while(j < tlen)        if(k == -1 || T[j] == T[k])            Next[++j] = ++k;        else            k = Next[k];}int t;int dp[N];int main () {    scanf ("%d",&t);    while (t--){        scanf ("%d",&tlen);        scanf ("%s",T);        getNext();        dp[0]=0;        int ans=0;        for (int i=1;i<=tlen;i++){            dp[i]=dp[Next[i]]+1;            dp[i]%=mod;            ans+=dp[i];            ans%=mod;        }        printf ("%d\n",ans);    }    return 0;}