1100 - 萌萌哒的第五题
Time Limit:10s Memory Limit:128MByte
Submissions:322Solved:67
DESCRIPTION
给出一个长度为m的字符串,请问有多少个长度为n的字符串不存在子串等于给出的字符串。为了简化问题,我们规定所有字符串只包含小写英文字母。
输入数据:
包含多组输入数据(<=15),每组数据:
第一行包含两个整数n和m(1 <= n,m <= 1000)
第二行包含一个长度为m的字符串,只含有小写字母。
INPUT
包含多组输入数据(<=15),每组数据: 第一行包含两个整数n和m(1 <= n,m <= 1000) 第二行包含一个长度为m的字符串,只含有小写字母。
OUTPUT
每组数据输出一行,表示答案,这个答案可能会很大,所以只需要输出答案对10^9+7求余的结果。
SAMPLE INPUT
2 2
aa
3 2
aa
SAMPLE OUTPUT
675
17525
SOLUTION
“玲珑杯”ACM比赛 Round #11
kmp求出给定字符串的next数组
通过next数组求出c[i][j]=字符串结尾能匹配模式串开头i个字母,在字符串结尾加上字母j,还能匹配多个个字母
d[i][j]=∑26k=0d[i−1][c[i−1][k]]∗(c[i−1][k]==j)
d[0][0]=1
ans=∑m−1i=0d[n][i]
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<time.h>
#include<math.h>
#include<list>
#include<cstring>
#include<fstream>
#include<queue>
#include<sstream>
//#include<memory.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define INF 1000000007
#define pll pair<ll,ll>
#define pid pair<int,double>
const int inf=1e9+7;
const int N = 1e3+5;
char p[N];
ll d[N][N];
int c[N][26];
ll dp(int n,int m){
d[0][0]=1;
for(int i=1;i<=n;++i){
fill(d[i],d[i]+m+1,0);
for(int j=0;j<m;++j){
for(int k=0;k<26;++k){
int to=c[j][k];
d[i][to]=(d[i][to]+d[i-1][j])%inf;
}
}
}
ll ans=0;
for(int i=0;i<m;++i){
ans=(ans+d[n][i])%inf;
}
return ans;
}
int Next[N];
void get_Nextval(char *P, int *next)
{
int j = 0;
int k = -1;
next[0] = -1;
int slen = strlen(P);
while( j < slen )
{
if( -1 == k || P[j] == P[k] )
{
++k;
++j;
if( P[j] != P[k] )
{
next[j] = k;
}
else
{
next[j] = next[k];
}
}
else
{
k = next[k];
}
}
}
void initC(int m){
get_Nextval(p,Next);
for(int i=0;i<m;++i){
for(int j=0;j<26;++j){
char a='a'+j;
int k=i;
while(k!=-1&&a!=p[k]){
k=Next[k];
}
c[i][j]=k+1;
}
}
}
int main()
{
//freopen("/home/lu/Documents/r.txt","r",stdin);
//freopen("/home/lu/Documents/w.txt","w",stdout);
int n,m;
while(~scanf("%d%d",&n,&m)){
scanf("%s",p);
initC(m);
printf("%lld\n",dp(n,m));
}
return 0;
}