Codeforces Round 578 (Div. 2) E题 Compress Words(扩展KMP)

题目链接

https://codeforces.com/problemset/problem/1200/E

思路

取当前串 s i s_{i} si的长度与当前答案 a n s ans ans的长度的最小值。

令 s i z = m i n ( ∣ s i ∣ , ∣ a n s ∣ ) siz = min(|s_{i}|,|ans|) siz=min(∣si∣,∣ans∣)。

将 s i s_{i} si的前 s i z siz siz部分和 a n s ans ans的后 s i z siz siz部分进行拼接,然后使用扩展KMP算法求出 z z z数组,根据 z z z数组的含义可以直接计算答案。

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 5;
int n;
string s[N];
// z[i]表示 s 和 s[i:] 匹配的最大前缀长度
vector<int> zfunc(const string& s) {
	int n = s.size();
	vector<int> z(n);
	for (int i = 1, l = 0, r = 0; i < n; i++) {
		if (i <= r) z[i] = min(z[i - l], r - i + 1);
		while (i + z[i] < n && s[i + z[i]] == s[z[i]]) z[i]++;
		if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1;
	}
	z[0] = n;
	return z;
}
void solve()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> s[i];
	}
	string ans = s[1];
	for (int i = 2; i <= n; i++)
	{
		string str = s[i];
		for (int j = max((int)((int)(ans.size()) - (int)(s[i].size())), 0ll); j < ans.size(); j++)
		{
			str.push_back(ans[j]);
		}
		vector<int>z = zfunc(str);
		int res = 0;
		for (int j = s[i].size(); j < str.size(); j++)
		{
			if (z[j] + j == str.size())
			{
				res = z[j];
				break;
			}
		}
		for (int j = res; j < s[i].size(); j++)
		{
			ans.push_back(s[i][j]);
		}
	}
	cout << ans << endl;
}
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	int test = 1;
	// cin >> test;
	for (int i = 1; i <= test; i++)
	{
		solve();
	}
	return 0;
}
相关推荐
Stanford_11062 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
千里马-horse4 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
格林威4 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
Lucis__5 小时前
再探类&对象——C++入门进阶
开发语言·c++
北京不会遇到西雅图6 小时前
【SLAM】【后端优化】不同优化方法对比
c++·机器人
jndingxin6 小时前
c++多线程(6)------ 条件变量
开发语言·c++
程序员莫小特6 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土7 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.8 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
蒙奇D索大8 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it