HDU-4749 Parade Show KMP算法 | DP

时间:2023-03-08 16:18:37

  题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4749

  题意:给两个串S和P,求S串中存在多少个与P串的大小关系一样的串。

  因为数字的范围是1<=k<=25之间,所以可以暴力的求25*25次KMP。当然完全没有必要这样做,在KMP的时候记录各个数的所表示的数就可以了,只需要求一遍KMP,复杂度降为O(25*n)。

 //STATUS:C++_AC_125MS_1596KB
#include <functional>
#include <algorithm>
#include <iostream>
//#include <ext/rope>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
#pragma comment(linker,"/STACK:102400000,102400000")
//using namespace __gnu_cxx;
//define
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1.0)
//typedef
typedef __int64 LL;
typedef unsigned __int64 ULL;
//const
const int N=;
const int INF=0x3f3f3f3f;
const int MOD=,STA=;
const LL LNF=1LL<<;
const double EPS=1e-;
const double OO=1e60;
const int dx[]={-,,,};
const int dy[]={,,,-};
const int day[]={,,,,,,,,,,,,};
//Daily Use ...
inline int sign(double x){return (x>EPS)-(x<-EPS);}
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T lcm(T a,T b,T d){return a/d*b;}
template<class T> inline T Min(T a,T b){return a<b?a:b;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
template<class T> inline T Min(T a,T b,T c){return min(min(a, b),c);}
template<class T> inline T Max(T a,T b,T c){return max(max(a, b),c);}
template<class T> inline T Min(T a,T b,T c,T d){return min(min(a, b),min(c,d));}
template<class T> inline T Max(T a,T b,T c,T d){return max(max(a, b),max(c,d));}
//End int next[N],s[N],p[N],w[],f[];
int T,n,m,k; void getnext(int *s,int len)
{
int j=,k=-;
next[]=-;
while(j<len){
if(k==- || s[k]==s[j])
next[++j]=++k;
else k=next[k];
}
} int solve()
{
int i,j,ret=,x,la=-;
for(i=j=;i<n;i++){
while(){
for(x=;x<=k;x++){
if(f[x]>=j){w[x]=-;continue;}
w[x]=p[i-j+f[x]];
}
if((j==-||w[s[j]]==-) || p[i]==w[s[j]])break;
j=next[j];
}
j++;
if(j==m && i>=la){la=i+m;ret++;}
}
return ret;
} int main(){
// freopen("in.txt","r",stdin);
int i,j,ans;
while(~scanf("%d%d%d",&n,&m,&k))
{
for(i=;i<n;i++){
scanf("%d",&p[i]);
}
mem(f,-);
for(i=;i<m;i++){
scanf("%d",&s[i]);
if(f[s[i]]==-)f[s[i]]=i;
}
p[n]=;s[m]=; getnext(s,m);
ans=solve(); printf("%d\n",ans);
}
return ;
}