UVA 1328 - Period KMP

时间:2022-11-22 08:48:24

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=36131

题意:给出一个长度为n的字符串,要求找到一些i,满足说从1~i为多个个的重复子串构成,并输出子串的个数。

题解:对kmp中预处理的数组的理解

//作者:1085422276
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include<bits/stdc++.h>
#include <map>
#include <stack>
typedef long long ll;
using namespace std;
const int inf = ;
inline ll read()
{
ll x=,f=;
char ch=getchar();
while(ch<''||ch>'')
{
if(ch=='-')f=-;
ch=getchar();
}
while(ch>=''&&ch<='')
{
x=x*+ch-'';
ch=getchar();
}
return x*f;
}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
ll temp,p;
if(b==)
{
x=;
y=;
return a;
}
p=exgcd(b,a%b,x,y);
temp=x;
x=y;
y=temp-(a/b)*y;
return p;
}
//*******************************
int n,p[];char a[];
int main()
{
int oo=;
while(scanf("%d",&n)!=EOF)
{
if(n==)break;
scanf("%s",a+);
memset(p,,sizeof(p));
int j=;
for(int i=;i<=n;i++)
{
while(j>&&a[j+]!=a[i])j=p[j];
if(a[j+]==a[i])j++;
p[i]=j;
}
cout<<"Test case #"<<oo++<<endl;
for(int i=;i<=n;i++)
{
if(p[i]>&&i%(i-p[i])==){
cout<<i<<" "<<i/(i-p[i])<<endl;
}
}
cout<<endl;
}
return ;
}

代码