【BZOJ4044】[Cerc2014] Virus synthesis【回文自动机】

【题目链接】

题解待补

/* Telekinetic Forest Guard */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 100005, maxq = maxn;

int n, q[maxq], ans, dp[maxn], id[26];

struct _ptree {
	int son[maxn][4], fail[maxn], suf[maxn], text[maxn], len[maxn], pcnt, last, tot;

	int newnode(int l) {
		for(int i = 0; i < 4; i++) son[pcnt][i] = 0;
		len[pcnt] = l;
		return pcnt++;
	}

	void init() {
		pcnt = last = tot = 0;
		newnode(0); newnode(-1);
		text[0] = -1; fail[0] = 1;
	}

	int getfail(int x) {
		for(; text[tot - len[x] - 1] != text[tot]; x = fail[x]);
		return x;
	}

	void add(int w) {
		text[++tot] = w;
		int now = getfail(last);
		if(!son[now][w]) {
			int v = newnode(len[now] + 2);
			fail[v] = son[getfail(fail[now])][w];
			if(len[v] <= 2) suf[v] = fail[v];
			else {
				int u = suf[now];
				for(; text[tot - len[u] - 1] != text[tot] || (len[u] + 2) * 2 > len[v]; u = fail[u]);
				suf[v] = son[u][w];
			}
			son[now][w] = v;
		}
		last = son[now][w];
	}

	void calc() {
		for(int i = 2; i < pcnt; i++) if(len[i] & 1) dp[i] = len[i];

		int h = 0, t = 0; dp[q[t++] = 0] = 1;
		while(h != t) for(int u = q[h++], i = 0; i < 4; i++) if(son[u][i]) {
			int v = son[u][i];
			dp[v] = min(dp[u] + 1, len[v] / 2 - len[suf[v]] + dp[suf[v]] + 1);
			ans = min(ans, n - len[v] + dp[v]);
			q[t++] = v;
		}
	}

} ptree;

char s[maxn];

int main() {
	int T; scanf("%d", &T);
	id['A' - 'A'] = 0; id['C' - 'A'] = 1; id['G' - 'A'] = 2; id['T' - 'A'] = 3;
	while(T--) {
		scanf("%s", s + 1); ans = n = strlen(s + 1);

		ptree.init();
		for(int i = 1; i <= n; i++) ptree.add(id[s[i] - 'A']);

		ptree.calc();
		printf("%d\n", ans);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值