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;
}
题意:求这个字符串每个前缀在字符串中出现了多少次。
思路: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;
}
相关文章推荐
- hdu 3336 Count the string (kmp + dp)
- HDU 3336 Count the string KMP+DP
- Hdu-3336 Count the string(KMP + DP)
- HDU 3336 Count the string 【KMP】【dp】
- HDU 3336 Count the String(KMP+DP)
- hdu 3336 Count the string KMP+DP
- HDU 3336 Count the string KMP+DP
- hdu -- 3336 Count the string(KMP + dp)
- HDU 3336 Count the string (kmp+dp)
- hdu 3336 Count the string KMP+DP
- Hdu 3336 Count the String(DP+KMP)(好题)
- Count the string HDU - 3336 KMP+DP
- HDU 3336 Count the string(kmp + dp)
- HDU 3336 Count the string 后缀数组 或 (KMP + DP)
- hdu 3336 Count the string 【kmp + dp】
- HDU - 3336 Count the string(KMP+DP)
- HDU 3336 Count the string ( KMP next函数的应用 + DP )
- Count the string (HDU_3336) 扩展KMP + dp
- hdu 3336 Count the string dp+KMP(失配函数)
- HDU 3336 Count the string (KMP + DP)