您的位置:首页 > 其它

HDU - 3336 Count the string(kmp+dp)

2017-10-25 20:05 519 查看
题目链接: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 0x3f3f3f3f
using 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
;
char S
, T
;
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
;
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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: