KMP板子题

Period POJ 1961

#include <iostream>
#include <cstdio>
#include <cstring>

#define Memset(x, a) memset(x, a, sizeof(x))
using  namespace std;

const int N = 1e6 + 10;
char s[N];
int Next[N];
int n;

// 性质 :一个字符串中任意循环元的长度必然是最小循环元长度的倍数
 
void  getNext(const char P[],int Next[]){
  int  m = strlen(P);           // strlen记录有效数组元素个数
  int i = 0, j;
  j = Next[0] = -1;
  while (i < m) {           // 扫一遍
    while (-1 != j && P[i] != P[j])
      j = Next[j];
    Next[++i] = ++j;
  }
}

 
int main(){
  int kase = 0;   // 用于输出的一个格式控制
  while (cin >> n && n){
    cin >> s;
    Memset(Next, 0);        // 将Next这个数组清空
    getNext(s, Next);     // Next中存的应该是减去一个单位长度的值 用 i - Next[i]得到的是单位长度
    cout << "Test case #" << ++kase << endl;
    for(int i = 2; i <= n; i++) {
      if(Next[i] > 0 && i % (i - Next[i]) == 0)   //  用i除 i - Next[i]得到的是循环次数
    }
    cout << endl;
  }
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/lightac/p/10584930.html
今日推荐