hdu 3336 Count the string(KMP)
2014-01-25 15:03
363 查看
题意:给出一个字符串,求它所有的前缀与它匹配的次数的和。
思路:KMP的应用……KMP构造的next数组中恰好包含着字符串的前缀的信息,因此,如果next数组没有转移到0,那么就说明他们有着公共的前缀,此时就是前缀和中间某一个串匹配上了。。。最后加上n个前缀本身就是答案……
代码:
思路:KMP的应用……KMP构造的next数组中恰好包含着字符串的前缀的信息,因此,如果next数组没有转移到0,那么就说明他们有着公共的前缀,此时就是前缀和中间某一个串匹配上了。。。最后加上n个前缀本身就是答案……
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<map> #include<queue> #include<set> #include<stack> #include<cmath> #include<vector> #define inf 0x3f3f3f3f #define Inf 0x3FFFFFFFFFFFFFFFLL #define eps 1e-9 #define pi acos(-1.0) using namespace std; typedef long long ll; const int maxn=200000+10; const int mod=10007; char str[maxn]; int next[maxn]; void getnext() { int n=strlen(str); next[0]=next[1]=0; for(int i=1;i<n;++i) { int j=next[i]; while(j&&str[i]!=str[j]) j=next[j]; next[i+1]=(str[i]==str[j])?j+1:0; } } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int t,n; scanf("%d",&t); while(t--) { scanf("%d",&n); scanf("%s",str); getnext(); int sum=0; for(int i=0;i<=n;++i) { if(next[i]) sum++; } sum=(sum+n)%mod; printf("%d\n",sum); } return 0; }
相关文章推荐
- hdu 3336 Count the string -KMP&dp
- HDU 3336 Count the string KMP+DP
- HDU 3336 Count the string (KMP next数组运用——统计前缀出现次数)
- Count the string (HDU_3336) 扩展KMP + dp
- hdu -- 3336 Count the string(KMP + dp)
- hdu 3336 Count the string(思维可水过,KMP)
- 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 + dp)
- |Hdu 3336|KMP|动态规划|Count the string
- HDU 3336 Count the string(kmp)
- Hdu 3336 Count the string[KMP next数组的理解]
- HDU-3336 Count the string(KMP)
- HDU 3336 Count the string(KMP 入门)
- hdu 3336 Count the string (DP+kmp)
- HDU 3336 Count the string【EXKMP+逆向思考 OR KMP】
- HDU 3336 Count the string 后缀数组 或 (KMP + DP)
- hdu 3336 Count the string(数据结构:KMP)