Dominating Patterns

可以用 SAM 来做,只不过空间常数稍大。

考虑建出后缀自动机后,用 fafa 树维护 Endpos\text{Endpos} 集合大小即可,非常经典的用 SAM 做的问题。

#include <bits/stdc++.h>
using namespace std;

const int N = 2e6 + 5;

int n;
string s[N], t;
int cnt[N];
vector<string> ans;
vector<int> G[N];

struct Node
{
	int len, fa, son[26];
}g[N];

int tot, last;
int f[N];

void extend(int c)
{
	int p = last;
	int np = last = ++tot;
	f[np] = 1;
	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[q].fa = g[np].fa = nq;
			for (; p && g[p].son[c] == q; p = g[p].fa) g[p].son[c] = nq;
		}
	}
}

void dfs(int u)
{
	for (int j : G[u])
	{
		dfs(j);
		f[u] += f[j];
	}
}

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