LightOj 1334 - Genes in DNA

很好的KMP题目,正反两次KMP (利用DFA的知识概念,统计每个节点的失败节点到根节点的的距离,即代码中的dis数组) ,接下来的问题就迎刃而解了  

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<vector>
#include<bitset>
#include<iterator>
#include<list>
#include<map>
#include<cstdlib>
#include<ctime>
#include<utility>
using namespace std;
#define L p->ch[0]
#define R p->ch[1]
#define KeyTree root->ch[1]->ch[0]
typedef unsigned long long LL;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int maxn = 1111111;
const int INF = 1 << 30;
const int mod = (int) (1e8);
const LL X = 123;
template<typename T>
T gcd(T a, T b) {
	return b ? gcd(b, a % b) : a;
}
int Next[maxn];
int dis[maxn];
char s[maxn], t[maxn];
int a[maxn], b[maxn];
void getnext(char s[], int n) {
	int i = 0, j;
	Next[0] = j = -1;
	dis[0] = 0;
	while (i < n) {
		if (j == -1 || s[i] == s[j]) {
			Next[++i] = ++j;
			dis[i] = dis[j] + 1;
		} else {
			j = Next[j];
		}
	}
}
int KMP(char s[], int n, char t[], int m, int c[]) {
	int i = 0, j = 0, ans = 0;
	while (i < n) {
		if (j == -1 || s[i] == t[j]) {
			++i, ++j;
			c[i - 1] = dis[j] - (j == m);
		} else {
			j = Next[j];
		}
		if (j == m) {
			++ans;
			j = Next[j];
		}
	}
	return ans;
}
int main() {
	//ios::sync_with_stdio(false);
	int T, cas;
	scanf("%d", &T);
	for (cas = 1; cas <= T; ++cas) {
		scanf("%s%s", s, t);
		int n = strlen(s);
		int m = strlen(t);
		getnext(t, m);
		KMP(s, n, t, m, a);

		reverse(t, t + m);
		reverse(s, s + n);

		getnext(t, m);
		KMP(s, n, t, m, b);

		LL ans = 0;
		reverse(b, b + n);

		ans = 0;
		a[n] = b[n] = 0;
		for (int i = 0; i < n; ++i) {
			ans = ans + 1LL * a[i] * b[i + 1];
		}
		printf("Case %d: %lld\n", cas, ans);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值