fzu 1901 Period II

简介: 点击打开链接fzu 1901 思路:kmp+next数组的应用 分析: 1 题目要求的找到所有满足S[i]=S[i+P] for i in [0..SIZE(S)-p-1]的前缀,并且长度为p。

点击打开链接fzu 1901


思路:kmp+next数组的应用
分析:
1 题目要求的找到所有满足S[i]=S[i+P] for i in [0..SIZE(S)-p-1]的前缀,并且长度为p。利用上面的式子可以等价的得到等式s[0,len-p-1] = s[p , len-1].
2 给个next数组的性质
   假设现在有一个字符串为ababxxxxabab。那么求出的next数组为00012001234,那么前缀和后缀最长的匹配数是4,然后下一个前缀和后缀匹配长度为next[4] = 2 , 然后下一个为next[2] = 0。
   所以有一个结论就是,假设当前求出的字符串的前缀和后缀的最长的匹配的长度为len,那么下一个满足的前缀和后缀互相匹配的长度为next[len]...依次
3 观察一下上面的等式,我们发现并不是我们所熟悉的前缀和后缀匹配的等价式。那么我们现在来看这个样列
            f z u f z u f z u f   长度为10
next    000 01 2 3 456 7
那么根据next数组就得到前缀和后缀的匹配长度依次为 7 4 1 0 ,那么这时候看看题目的p的可能长度为 3 6 9 10,那么有没有发现规律。

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
using namespace std;

#define MAXN 1000010

int Case;
int next[MAXN];
char words[MAXN];

void getNext(){
   int len = strlen(words);
   next[0] = next[1] = 0;

   for(int i = 1 ; i < len ; i++){
      int j = next[i];
      while(j && words[i] != words[j])
          j = next[j];
      next[i+1] = words[i] == words[j] ? j+1 : 0;
   }
}

int main(){
   int t = 1;
   scanf("%d" , &Case);
   while(Case--){
      scanf("%s" , words);
      getNext();
      int len = strlen(words);
      int i = next[len];
      int ans = 1;
      while(i){
         ans++;
         i = next[i];
      }
      printf("Case #%d: %d\n" , t++ , ans);
      i = next[len];
      while(i){
         printf("%d " , len-i);
         i = next[i];
      }
      printf("%d\n" , len);
   }
   return 0;
}





目录
相关文章
hdu 1358 Period
点击打开链接hdu 1358 思路:kmp+最小循环节 分析: 1 题目要求的是给定一个长度为n的字符串,求出字符串的所有前缀字符串中该字符串刚好由k个最小循环节够成,由于题目要求k最大那么就是这个循环节最小 2 只要先求出next数...
777 0
|
机器学习/深度学习
FZU 1683 纪念SlingShot
点击打开FZU1683 思路: 矩阵快速幂 分析: 1 题目给定f(n) = 3*f(n-1)+2*f(n-2)+7*f(n-3) , f(0) = 1 , f(1) = 3 , f(2) = 5 ,给定n求f(0)+.
903 0
|
存储
FZU 2039 pets
点击打开链接FZU2039 思路:二分图水题 分析:只要建模然后套模板ok 代码: /*DFS求二分图的最大匹配*/ #include #include #include #include using namespace std; ...
1021 0
FZU Problem 2132 LQX的作业
点击打开链接 题意:题目要求选择n个0~1之间的数拍完序之后第m个小于等于x的概率 思路:1~0直接选择一个数小于等于x的概率为x,那么选择i个数都小于等于x的概率为x^i。
1033 0
[usaco] Number Triangles
<center><h1>Number Triangles</h1></center> <p>Consider the number triangle shown below. Write a program that calculates the highest sum of numbers that can be passed on a route that starts at the to
1675 0
|
索引
ZOJ 1122. Clock
  http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=122    题目:给出两个时刻 t1 (h1:m1), t2 (h2:m2); 其中 h1,h2 表示小时属于 [1, 12] , m1, m2表示分钟属于 [0, 59],t1 到 t2 的间隔跨度小于 12 小时。
763 0
|
机器学习/深度学习 人工智能
FZU 1692 Key problem
点击打开FZU 1692 思路: 构造矩阵+矩阵快速幂 分析: 1 题目的意思是有n个人构成一个圈,每个人初始的有ai个苹果,现在做m次的游戏,每一次游戏过后第i个人能够增加R*A(i+n-1)%n+L*A(i+1)%n 个苹果(题目有错)...
830 0
|
人工智能 算法 搜索推荐
ZOJ 3499. Median
    地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4322     题意:寻找中位数。对于一个(浮点数)数组,如果含有奇数个元素,“中位数”就是排序后位于数组中间那个。
1301 1