BZOJ 1355 & KMP

BZOJ放这种丝帛我也是醉了...

  不过来填一下求最小循环节的坑...

  以这道题为例,相同文本串粘起来的串中取一小节,可以把任意一个字符看做文本串头.

  那么我们一次KMP求出next函数然后显见,最后一个字符它会与上一个循环串的尾匹配,所以减一减就好啦...

/*==========================================================================
# Last modified: 2016-03-03 11:11
# Filename: 1355.cpp
# Description: 
==========================================================================*/
#define me AcrossTheSky 
#include <cstdio> 
#include <cmath> 
#include <ctime> 
#include <string> 
#include <cstring> 
#include <cstdlib> 
#include <iostream> 
#include <algorithm> 
  
#include <set> 
#include <map> 
#include <stack> 
#include <queue> 
#include <vector> 
 
#define lowbit(x) (x)&(-x) 
#define FOR(i,a,b) for((i)=(a);(i)<=(b);(i)++) 
#define FORP(i,a,b) for(int i=(a);i<=(b);i++) 
#define FORM(i,a,b) for(int i=(a);i>=(b);i--) 
#define ls(a,b) (((a)+(b)) << 1) 
#define rs(a,b) (((a)+(b)) >> 1) 
#define getlc(a) ch[(a)][0] 
#define getrc(a) ch[(a)][1] 
 
#define maxn 100000 
#define maxm 100000 
#define pi 3.1415926535898 
#define _e 2.718281828459 
#define INF 1070000000 
using namespace std; 
typedef long long ll; 
typedef unsigned long long ull; 
 
template<class T> inline 
void read(T& num) { 
    bool start=false,neg=false; 
    char c; 
    num=0; 
    while((c=getchar())!=EOF) { 
        if(c=='-') start=neg=true; 
        else if(c>='0' && c<='9') { 
            start=true; 
            num=num*10+c-'0'; 
        } else if(start) break; 
    } 
    if(neg) num=-num; 
} 
/*==================split line==================*/ 
char s[maxn];
int p[maxn],len=0;
void getfail(){
	int j=0; p[1]=0;
	FORP(i,2,len){
		while (j && s[i]!=s[j+1]) j=p[j];
		if (s[i]==s[j+1]) j++;
		p[i]=j;
	}
}
int main(){ 
	int n; read(n);// getchar();
	char c;
	while ((c=getchar())!='
')	s[++len]=c;
	getfail();
	printf("%d",len-p[len]);
}
Sometimes it s the very people who no one imagines anything of. who do the things that no one can imagine.
原文地址:https://www.cnblogs.com/YCuangWhen/p/5237995.html