HDU6153-A Secret

来源:互联网 发布:淘宝日本代购退换 编辑:程序博客网 时间:2024/06/05 09:57

A Secret

                                                                        Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 256000/256000 K (Java/Others)
                                                                                                Total Submission(s): 1489    Accepted Submission(s): 554


Problem Description
Today is the birthday of SF,so VS gives two strings S1,S2 to SF as a present,which have a big secret.SF is interested in this secret and ask VS how to get it.There are the things that VS tell:
  Suffix(S2,i) = S2[i...len].Ni is the times that Suffix(S2,i) occurs in S1 and Li is the length of Suffix(S2,i).Then the secret is the sum of the product of Ni and Li.
  Now SF wants you to help him find the secret.The answer may be very large, so the answer should mod 1000000007.
 

Input
Input contains multiple cases.
  The first line contains an integer T,the number of cases.Then following T cases.
  Each test case contains two lines.The first line contains a string S1.The second line contains a string S2.
  1<=T<=10.1<=|S1|,|S2|<=1e6.S1 and S2 only consist of lowercase ,uppercase letter.
 

Output
For each test case,output a single line containing a integer,the answer of test case.
  The answer may be very large, so the answer should mod 1e9+7.
 

Sample Input
2aaaaaaaabababababa
 

Sample Output
1319
Hint
case 2: Suffix(S2,1) = "aba",Suffix(S2,2) = "ba",Suffix(S2,3) = "a".N1 = 3,N2 = 3,N3 = 4.L1 = 3,L2 = 2,L3 = 1.ans = (3*3+3*2+4*1)%1000000007.
 

Source
2017中国大学生程序设计竞赛 - 网络选拔赛
 

题意:给你两个字符串,求出第二个字符串所有后缀在第一个字符串出现的次数*后缀长度的和

解题思路:kmp,先将连个字符串反一下,再求出第二个字符串的next数组,然后两个字符串进行匹配,当不匹配的时候,根据已匹配长度更新答案


#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <map>#include <set>#include <stack>#include <queue>#include <vector>#include <bitset>#include <functional>using namespace std;#define LL long longconst int INF = 0x3f3f3f3f;const LL mod = 1e9 + 7;char s1[1000009], s2[1000009];int nt[1000009], len1, len2;LL ans;void kmp(){    int i = 0, j = 0;    while (i < len1)    {        if (s1[i] == s2[j] || j == -1) i++, j++;        else ans += 1LL * (1 + j)*j / 2, ans %= mod, j = nt[j];    }    while (j) ans += 1LL * (1 + j)*j / 2, ans %= mod, j = nt[j];}int main(){    int t;    scanf("%d", &t);    while (t--)    {        scanf("%s%s", s1, s2);        len1 = strlen(s1), len2 = strlen(s2);        for (int i = 0; i < len1 / 2; i++) swap(s1[i], s1[len1 - 1 - i]);        for (int i = 0; i < len2 / 2; i++) swap(s2[i], s2[len2 - 1 - i]);        nt[0] = -1, ans = 0;        for (int i = 0; i < len2; i++)        {            int k = nt[i];            while (s2[i] != s2[k] && k >= 0) k = nt[k];            nt[i + 1] = k + 1;        }        kmp();        printf("%lld\n", ans);    }    return 0;}

原创粉丝点击