Problem Description It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
Input The first line is a single integer T, indicating the number of test cases.
Output For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.
Sample Input 1 4 abab
Sample Output 6 |
题意:求每个前缀在字符串中匹配的次数的总和,并取模;
思路:运用KMP和DP,dp[i]表示 i 为结尾的串的个数,对我来说比较抽象,可以在模拟一下;
上代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N=200005;
const int MO=10007;
char s[N];
int Next[N],n;
int dp[N];
void get_Next()
{
int i=0,j=-1;
Next[0]=-1;
while(i<n)
{
if(j==-1||s[i]==s[j])
Next[++i]=++j;
else
j=Next[j];
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(dp,0,sizeof(dp));
int ans=0,i,k,l;
scanf("%d",&n);
scanf("%s",s);
get_Next();
for(i=1;i<=n;i++)
{
dp[i]=dp[Next[i]]+1;
ans=(ans+dp[i])%MO;
}
printf("%d\n",ans);
}
}