2016多校Contest 4 1001 HDU5769(dp+kmp算法)

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.
 

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.
 

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: 3
Hint
In 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;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值