zoukankan      html  css  js  c++  java
  • poj2752Seek the Name, Seek the Fame【kmp next数组应用】

    大意:给你一个串,如果这个串存在一个长度为n的前缀串,和长度为n的后缀串,并且这两个串相等,则输出他们的长度n。求出所有的长度n

    例如

    ‘alala'. Potential prefix-suffix strings of S are {'a', 'ala', 'alala'}

    分析:考察对于next数组的理解

    next数组表示i之前的k个字符与该串钱k个字符匹配

    所以

    next[l] 就表示最大后缀满足与前缀相同的最大字串

    然后  在对获得的字串进行同样的求解  最终得到结果

    代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 using namespace std;
     5 
     6 const int maxn = 400005;
     7 
     8 int next[maxn];
     9 int ans[maxn];
    10 
    11 void get(char *s) {
    12     int l = strlen(s);
    13     int j = 0, k = -1;
    14     next[0] = -1;
    15     while(j < l) {
    16         if(k == -1 || s[j] == s[k]) {
    17             next[++j] = ++k;
    18         } else {
    19             k = next[k];
    20         }
    21     }
    22 }
    23 char s[maxn];
    24 
    25 int main() {
    26     while(EOF != scanf("%s",s)) {
    27         get(s);
    28         int tot = 0;
    29         int k = strlen(s);
    30         while(k) {
    31             ans[tot++] = k;
    32             k = next[k];
    33         }
    34         for(int i = tot - 1; i >= 0; i--) {
    35             printf(i == tot - 1 ? "%d" : " %d", ans[i]);
    36         } puts("");
    37     }
    38 }
    View Code
  • 相关阅读:
    实习日记11
    实习日记10
    实习日记9
    实习日记7
    我自己的颜色库
    实习日记5
    实习日记4
    算法导论2:几个习题 2016.1.2
    算法导论1:插入排序和归并排序 2016.1.1
    和算法导论没什么关系0.手电筒过桥问题详解
  • 原文地址:https://www.cnblogs.com/zhanzhao/p/4761660.html
Copyright © 2011-2022 走看看