Substring
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 79 Accepted Submission(s): 31
Problem Description
?? is practicing his program skill, and now he is given a string, he has to calculate the total number of its distinct substrings.
But ?? thinks that is too easy, he wants to make this problem more interesting.
?? likes a character X very much, so he wants to know the number of distinct substrings which contains at least one X.
However, ?? is unable to solve it, please help him.
But ?? thinks that is too easy, he wants to make this problem more interesting.
?? likes a character X very much, so he wants to know the number of distinct substrings which contains at least one X.
However, ?? is unable to solve it, please help him.
Input
The first line of the input gives the number of test cases T;T test cases follow.
Each test case is consist of 2 lines:
First line is a character X, and second line is a string S.
X is a lowercase letter, and S contains lowercase letters(‘a’-‘z’) only.
T<=30
1<=|S|<=10^5
The sum of |S| in all the test cases is no more than 700,000.
Each test case is consist of 2 lines:
First line is a character X, and second line is a string S.
X is a lowercase letter, and S contains lowercase letters(‘a’-‘z’) only.
T<=30
1<=|S|<=10^5
The sum of |S| in all the test cases is no more than 700,000.
Output
For each test case, output one line containing “Case #x: y”(without quotes), where x is the test case number(starting from 1) and y is the answer you get for that case.
Sample Input
2 a abc b bbb
Sample Output
Case #1: 3 Case #2: 3HintIn first case, all distinct substrings containing at least one a: a, ab, abc. In second case, all distinct substrings containing at least one b: b, bb, bbb.
官方题解:
对于这个问题,显然可以进行DP:
令dp[i]表示到i结尾的字符串可以表示的不同含义数,那么考虑两种转移:
末尾不替换含义:dp[i - 1]
末尾替换含义:dp[i - |B|] (A.substr(i - |B| + 1,|B|) = B)
那么对于末尾替换含义的转移,需要快速判断BBB能不能和当前位置的后缀匹配,kmp或者hash判断即可。
复杂度:O(N)
AC代码:#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100005;
const int MOD = 1000000007;
int T;
char a[N], b[N];
int n, m, jump[N];
int dp[N];
int main() {
scanf("%d", &T);
int cas = 0;
while (T--) {
scanf("%s%s", a + 1, b + 1);
n = strlen(a + 1); m = strlen(b + 1);
int j = 0;
for (int i = 2; i <= m; i++) {//kmp算法
while (j && b[i] != b[j + 1]) j = jump[j];
if (b[i] == b[j + 1]) j++;
jump[i] = j;
}
j = 0;
dp[0] = 1;
for (int i = 1; i <= n; i++) {
while (j && a[i] != b[j + 1]) j = jump[j];
if (a[i] == b[j + 1]) j++;
dp[i] = dp[i - 1];
if (j == m) {
dp[i] = (dp[i] + dp[i - m]) % MOD;
j = jump[j];
}
}
printf("Case #%d: %d\n", ++cas, dp[n]);
}
return 0;
}