一只可爱的串串小姐(Luogu P1470 [IOI 1996 / USACO2.3] 最长前缀 Longest Prefix)

P1470 [IOI 1996 / USACO2.3] 最长前缀 Longest Prefix

题目描述

在生物学中,一些生物的结构是用包含其要素的大写字母序列来表示的。生物学家对于把长的序列分解成较短的序列(即元素)很感兴趣。

如果一个集合 \(P\) 中的元素可以串起来(元素可以重复使用)组成一个序列 \(S\),那么我们认为序列 \(S\) 可以分解为 \(P\) 中的元素。元素不一定要全部出现(如下例中 BBC 就没有出现)。举个例子,序列 ABABACABAAB 可以分解为下面集合中的元素:{A,AB,BA,CA,BBC}

序列 \(S\) 的前面 \(k\) 个字符称作 \(S\) 中长度为 \(k\) 的前缀。设计一个程序,输入一个元素集合以及一个大写字母序列,设 \(S'\) 是序列 \(S\) 的最长前缀,使其可以分解为给出的集合 \(P\) 中的元素,求 \(S'\) 的长度 \(k\)

输入格式

输入数据的开头包括若干个元素组成的集合 \(P\),用连续的以空格分开的字符串表示。字母全部是大写,数据可能不止一行。元素集合结束的标志是一个只包含一个 . 的行,集合中的元素没有重复。

接着是大写字母序列 \(S\),用字符串表示,每 \(76\) 个字符换一行。

输出格式

只有一行,输出一个整数,表示 \(S\) 符合条件的前缀的最大长度。

输入输出样例 #1

输入 #1

A AB BA CA BBC
.
ABABACABAABC

输出 #1

11

说明/提示

【数据范围】

对于 \(100\%\) 的数据,\(1\le \text{card}(P) \le 200\)\(1\le |S| \le 2\times 10^5\)\(P\) 中的元素长度均不超过 \(10\)

翻译来自 NOCOW。

我们可以使用KMP。
先处理出给定集合的每个元素在原串中出现的位置。
他让求最长前缀,如何?
我们可以使用 \(\mathcal{dp}\)dp[i] 表示 \(1\sim i\) 是否可以被覆盖,那么转移呢?
假设我们集合中的一个元素在原串中出现的一个位置是 \(l\sim r\),那么只要 dp[l - 1]true,那么 dp[r] 就是 true

点击查看代码
#include <iostream>
#include <string>
#include <vector>
#include <cstring>

using std::cin;
using std::cout;
const int N = 2e5 + 10;
const int M = 4e7 + 10;

int tot;
std::string s[210];
int bor[N];
int kmp[N];
int dp[N];
std::vector<int> tong[N];

int main()
{
	int tot = 0;
	while (cin >> s[++tot])
	{
		if (s[tot].size() == 1 && s[tot][0] == '.')
		{
			tot--;
			break;
		}
	}
	std::string all = "";
	std::string now;
	while (cin >> now)
		all += now;
	int sizeall = all.size();
	all = " " + all;
	for (int k = 1; k <= tot; ++k)
	{
		int nowsize = s[k].size();
		s[k] = " " + s[k];
		bor[1] = 0;
		int j = 0;
		for (int i = 2; i <= nowsize; ++i)
		{
			while (j && s[k][j + 1] != s[k][i])
				j = bor[j];
			if (s[k][j + 1] == s[k][i])
				j++;
			bor[i] = j;
		}
		j = 0;
		for (int i = 1; i <= sizeall; ++i)
		{
			while (j && s[k][j + 1] != all[i])
				j = bor[j];
			if (s[k][j + 1] == all[i])
				j++;
			if (j == nowsize)
				tong[i - nowsize + 1].push_back(i);
		}
	}
	dp[0] = true;
	int ans = 0;
	for (int i = 1; i <= sizeall; ++i)
	{
		for (auto it : tong[i])
		{
			if (dp[i - 1])
				dp[it] = true, ans = std::max(ans, it);
		}
	}
	cout << ans << '\n';
	return 0;
}
posted @ 2025-11-23 09:13  SigmaToT  阅读(8)  评论(0)    收藏  举报