HDU 6153 A Secret (KMP)
Posted dwtfukgv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 6153 A Secret (KMP)相关的知识,希望对你有一定的参考价值。
题意:给定两个串,求其中一个串 s
的每个后缀在另一个串 t
中出现的次数。
析:首先先把两个串进行反转,这样后缀就成了前缀。然后求出 s 的失配函数,然后在 t 上跑一遍,如果发现不匹配了或者是已经完全匹配了,要计算,前面出现了多少个串的长度匹配也就是 1 + 2 + 3 + .... + j 在 j 处失配,然后再进行失配处理。注意别忘了,匹配完还要再加上最后的。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #include <list> #include <assert.h> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define fi first #define se second #define pb push_back #define sqr(x) ((x)*(x)) #define ms(a,b) memset(a, b, sizeof a) #define sz size() #define pu push_up #define pd push_down #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 1e20; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1e6 + 100; const LL mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c) { return r > 0 && r <= n && c > 0 && c <= m; } char s[maxn], t[maxn]; int f[maxn]; void getFail(){ f[0] = f[1] = 0; for(int i = 1; i < n; ++i){ int j = f[i]; while(j && s[j] != s[i]) j = f[j]; f[i+1] = s[i] == s[j] ? j+1 : 0; } } int main(){ int T; cin >> T; while(T--){ scanf("%s", t); int len = strlen(t); reverse(t, t + len); scanf("%s", s); n = strlen(s); reverse(s, s + n); getFail(); LL ans = 0; int j = 0; for(int i = 0; i < len; ++i){ while(j && s[j] != t[i]){ ans = (ans + (LL)j * (j+1LL) / 2) % mod; j = f[j]; } if(s[j] == t[i]) ++j; if(j == n){ ans = (ans + (LL)j * (j+1LL) / 2 ) % mod; j = f[j]; } } while(j){ ans = (ans + (LL)j * (j+1LL) / 2) % mod; j = f[j]; } printf("%I64d\n", ans); } return 0; }
以上是关于HDU 6153 A Secret (KMP)的主要内容,如果未能解决你的问题,请参考以下文章