ADAPHOTO - Ada and Terramorphing

经典后缀自动机题。

考虑对 ss 建立后缀自动机,然后从前往后枚举 tt 的每个字符,从后缀自动机起点开始搜,如果现在的点往这个字符有边,直接往这边走,并且长度 +1+1。否则一直跳 fafa,更新长度即可。

复杂度 O(n+m)O(n+m),拿下了 Rank 1。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;

const int N = 2e6 + 5;

struct Node
{
	int son[4], fa, len;
}g[N];
string s1, s2;

int last = 1, tot = 1;

void extend(int c)
{
	int p = last, np = last = ++tot;
	g[np].len = g[p].len + 1;
	for (; p && g[p].son[c] == 0; p = g[p].fa)
	{
		g[p].son[c] = np;
	}
	if (!p) g[np].fa = 1;
	else
	{
		int q = g[p].son[c];
		if (g[q].len == g[p].len + 1) g[np].fa = q;
		else
		{
			int nq = ++tot;
			g[nq] = g[q];
			g[nq].len = g[p].len + 1;
			g[np].fa = g[q].fa = nq;
			for (; p && g[p].son[c] == q; p = g[p].fa) g[p].son[c] = nq;
		}
	}
}

int main()
{
	ios::sync_with_stdio(0), cin.tie(nullptr), cout.tie(nullptr);
	cin >> s1 >> s2;
	for (char i : s1)
	{
		int p = (i == '-' ? 0 : (i == '^' ? 1 : (i == '~' ? 2 : 3)));
		extend(p);
	}
	int ans = 0, u = 1, len = 0;
	int c = 0;
	for (char i : s2)
	{
		int p = (i == '-' ? 0 : (i == '^' ? 1 : (i == '~' ? 2 : 3)));
		c++;
		while (u && !g[u].son[p])
		{
			u = g[u].fa;
			len = g[u].len;
		}
		if (u == 0) u = 1;
		if (g[u].son[p])
		{
			len++;
			u = g[u].son[p];
		}
		ans = max(ans, len);
	}
	cout << ans << "\n";
	return 0;
}
posted @   HappyBobb  阅读(7)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示