http://acm.hdu.edu.cn/showproblem.php?pid=3336
解题报告:刚开始用的是暴力的方法,就是每次往next数组中加一个元素,然后再在整个数组中进行查找,虽然加了很多的优化,但是还是无限的TLE中。(拒绝暴力,另寻他路)。
直接用next数组的意义,不过这次的求解next的方法与上次有些不同,暂且叫作方法二吧:
void get_next() { int i=0,j=-1; next[0]=-1; while(i<n) { while(j>-1&&a[j]!=a[i]) { j=next[j]; } i++; j++; next[i]=j; printf("next[%d]=%d\n",i,next[i]); } }
与原来的算法有什么不同呢?虽然也定义next[0]=-1,但后面绝不会出现-1,除了next[0],其他模式值next[j]=k(0≤k<j)的意义可以简单看成是:下标为j的字符的前面最多k个字符与开始的k个字符相同,这里并不要求a[j]!=a[k]。其实next[0]也可以定义为0(后面给出的求串的模式值的函数和串的模式匹配的函数,是next[0]=0的),这样,next[j]=k(0≤k<j)的意义都可以简单看成是:下标为j的字符的前面最多k个字符与开始的个字符相同。这样子问题就简单多了!
#include<cstdio> #include<cstring> using namespace std; const int MAX =200000+5; char a[MAX]; int next[MAX],n; void get_next() { int i=0,j=-1; next[0]=-1; while(i<n) { while(j>-1&&a[j]!=a[i]) { j=next[j]; } i++; j++; next[i]=j; printf("next[%d]=%d\n",i,next[i]); } } int main() { int T; scanf("%d",&T); while(T--) { int ans=0; scanf("%d %s",&n,a); get_next(); ans+=n+next[n]; for(int i=0;i<n;i++) { if(next[i]>0&&next[i]+1!=next[i+1]) { ans+=next[i]; } } printf("%d\n",ans%10007); } return 0; }
相关推荐
hdu ACM代码 每种算法都有分类 大三了,没有时间弄ACM,这些要删了
HDU-1711 Number Sequence(KMP算法)For each test case, you should output one line wh
next[i]的含义是在str[i]之前的字符串str[0...i]中,必须以str[i-1]结尾的后缀子串(不能包含str[0])与必须以str[0]开头的前
hdu动态规划算法集锦
很实用的算法讲解,hdu的lcy老师讲解,还不错!!
HDU的ACM,非常的好 涉及了很多算法,例如二分匹配、博弈、组合、最小生成树、搜索、动态规划、贪心算法
acm 技术大牛 课件 HDU 自学必备课件 全套齐全 (lecture_01)初识ACM (lecture_02)简单数学题 (lecture_03)递推求解 (lecture_04)动态规划(1)_ (lecture_05)计算几何基础_ (lecture_06)母函数 (lecture_...
杭州电子科技大学oj平台上的第1010题,是关于搜索的题目,很不错的题
杭电ACM 培训课件,包括各种常用的算法,并结合例题详细的讲解,对提高算法思想用很大帮助
算法-数塔(HDU-2084).rar
八数码的A*算法~不是很高效,但是很适合刚刚学这个算法的朋友们
HDU的1250,主要是利用高精度加法,但是代码有点繁琐,效率不是很高
The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105. Input Input...
杭电ACMhdu1163
算法-超级楼梯(HDU-2040)(包含源程序).rar
HDU1059的代码
算法设计与分析实验六:使用动态规划算法解决存钱问题(java实现、hdu1114)(csdn)————程序
hdu1001解题报告
hdu 1574 passed sorce
算法-六度分离(HDU-1869)(包含源程序).rar