hdu 3336 Count the string(★)
来源:互联网 发布:mac怎么启用flash 编辑:程序博客网 时间:2024/06/05 19:54
题意:给一个字符串,输出包括从1到len长 字符串前缀的总个数
YY: 基本思想是 KMP + DP,主要看KMP
kmp思想:对字符串进行预处理,记录与当前位置i后缀相同的“最近”位置,用next[i]记录,
保证 s[1 .. i] 中 s[i - next[i] + 1 .. i] 与 s[1 .. next[i]] 是相同的,
以便在某处字符不匹配时,不用重新从头判断一遍,只要从对应的next[i]即可,
因为中间有部分与自身重叠,减少了不必要的判断,实现见代码。
例1:
i : 1234567
字符串 : abcabab
next[i] : 0001212
例2:
i : 12345678
字符串 : abababab
next[i] : 00123456
例3:
i : 123456789
字符串: ababcdabd
next[i]: 001200120
DP:
cns[]数组:以 i 结尾的串中所有前缀的计数和
状态转移方程: cns[i] = cns[next[i]] + 1;
i : 123456
字符串: ababab
cns[i]: 112233
比如当i等于5时,ababa中后面的aba与前面的aba重叠,
以第三个a为结尾的前缀总数对应于前面的aba的前缀数+1(ababa)
<pre name="code" class="cpp">#include <stdio.h>#include <string.h>const int MAX_LEN = 200005; int next[MAX_LEN]; char s[MAX_LEN];int cns[MAX_LEN];int main(){ int cas; scanf("%d",&cas); while(cas--) { int len; int flag; scanf("%d",&len); scanf("%s",s+1); //!!!!!!!!!!!!! next[1] = 0; flag = 0; for(int i=2;i<=len;i++) { while(flag > 0 && s[flag+1]!=s[i]) flag = next[flag]; if(s[flag+1] == s[i]) flag++; next[i] = flag; } int sum=0; memset(cns,0,sizeof(cns)); for(int i=1;i<=len;i++) { cns[i] = (cns[next[i]] + 1)%10007; sum = (sum+cns[i])%10007; } printf("%d\n",sum); } return 0;}
- hdu 3336 Count the string(★)
- 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)
- 【HDU 3336】Count the string(kmp)
- 【HDU-3336-count the string】(KMP)
- HDU 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- HDU-Count the string -3336
- hdu 3336 Count the string
- ocp-35
- ESP8266-01细玩笔记(二)
- Ad-hoc网络
- HashMap实现原理分析
- ocp-36
- hdu 3336 Count the string(★)
- poj 1952 最长递减子序列+求个数
- 获取当前jvm下的所有线程
- 读懂diff
- JAVA设计模式之单件模式
- hdoj 2855 Fibonacci Check-up 【打表找规律 + 矩阵快速幂】
- Word Search II
- jasperReport生成html图片显示问题
- 把不是镂空图的图片 转化成 镂空图