hdu 3336 Count the string(数据结构:KMP)
2014-08-13 23:47
357 查看
给出一个字符串,求出其所有前缀在当前串中出现的次数和
我刚开始的做法是枚举所有的前缀,用kmp判断匹配
数据量200,000。时间复杂度O(4e10),毫无疑问TLE了
后来才知道是利用next性质来做
对于abab
我们从下标1开始
则很容易得到
令dp[i]为以p[i]结尾的前缀个数
根据next数组含义,我们很容易得到dp[i] = dp[str[i]]+1;
如对于abab
dp[1]对应于:a(前面的)
dp[2]对应于:ab(前面的)
dp[3]对应于:a(后面的),
aba
dp[4]对应于:ab(后面的),
abab
故和为6个
感觉这个题比较蛋疼的地方就是求next要从下标1开始。。。由于对kmp理解的还不够透彻,我只会从下标0开始
代码如下:
我刚开始的做法是枚举所有的前缀,用kmp判断匹配
数据量200,000。时间复杂度O(4e10),毫无疑问TLE了
后来才知道是利用next性质来做
对于abab
我们从下标1开始
则很容易得到
next[1] = 0 next[2] = 0 next[3] = 1 next[4] = 2
令dp[i]为以p[i]结尾的前缀个数
根据next数组含义,我们很容易得到dp[i] = dp[str[i]]+1;
如对于abab
dp[1]对应于:a(前面的)
dp[2]对应于:ab(前面的)
dp[3]对应于:a(后面的),
aba
dp[4]对应于:ab(后面的),
abab
故和为6个
感觉这个题比较蛋疼的地方就是求next要从下标1开始。。。由于对kmp理解的还不够透彻,我只会从下标0开始
代码如下:
#include <cstdio> #include <cstring> #define MAXN 200100 #define LL long long #define MOD 10007 using namespace std; int n; int next[MAXN], dp[MAXN]; char str[MAXN]; void get_next(char p[]) { next[1] = 0; int i, j = 0; for(int i=2; i<=n; ++i) { while(j>0 && str[j+1]!=str[i]) j = next[j]; if(str[j+1] == str[i]) ++j; next[i] = j; } } int main(void) { int T; scanf("%d", &T); while(T--) { scanf("%d", &n); scanf("%s", str+1); get_next(str+1); int sum = 0; dp[0] = 0; for(int i=1; i<=n; ++i) { dp[i] = dp[next[i]]+1; sum = (sum+dp[i])%MOD; } printf("%d\n", sum); } return 0; }
相关文章推荐
- HDU 3336 Count the string KMP+DP
- hdu 3336 Count the string(KMP)
- HDU 3336 Count the string KMP
- [HDU 3336]Count the String[kmp]
- HDU--杭电--3336--Count the string--KMP--说是KMP,实际我是用的滑动取值,别人教的
- HDU 3336 Count the string ( KMP next函数的应用 + DP )
- HDU 3336 Count the string kmp+dp
- HDU 3336 Count the string(KMP:串前缀匹配自身+DP)
- Hdu 3336 Count the string[KMP next数组的理解]
- HDU 3336 Count the string(KMP+dp)
- HDU 3336 Count the string KMP+DP
- HDU 3336 Count the string(KMP)
- hdu 3336 Count the string(KMP)
- hdu 3336【Count the string】(KMP)
- hdu 3336 Count the string(KMP)
- HDU 3336 Count the string KMP
- hdu 3336 Count the string KMP+DP
- [HDU 3336]Count the String[kmp][DP]
- hdu 3336 Count the string (DP+kmp)
- Hdu 3336 Count the string (KMP+DP 前缀出现次数和)