[str记录]abc254G Prefix Concatenation
题意简述:给定两个串 ,求至少用 的几个前缀才能拼出 。。
考虑 dp。设 表示至少用 的几个前缀才能拼出 的前 个字符。转移方程:。这看着是个 的式子,考虑优化。
把 打出来看看规律。
1 1 1 2 2 3 3 3
发现 单调不降。
浅证:若 ,让拼成 的最后一个字符串去掉一个字母,显然仍是一个前缀,可以变成 的情况,矛盾。
所以只需对每个 找出最小的 满足 是 的前缀,即可。这看着很像 kmp 的 next
数组。把 作为一个整体进行自我匹配,即得。
//time : 2022-06-27 11:51
//problem url : https://atcoder.jp/contests/abc257/tasks/abc257_g
//status : not submitted
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
const int M = 1000005;
string s, t; int dp[M], m, n, nxt[M];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin >> s >> t; n = s.length(); m = t.length();
s = s + '#' + t;
memset(dp, 0x3f, sizeof dp);
dp[0] = 0;
for(int i = 1; i <= n+m; i++){
int j = nxt[i-1];
while(j > 0 && s[i] != s[j]) j = nxt[j-1];
if(s[i] == s[j]) ++j;
nxt[i] = j;
}
for(int i = 1; i <= m; i++){
dp[i] = dp[i-nxt[n+i]] + 1;
}
printf("%d\n", dp[m] >= 0x3f3f3f3f ? -1 : dp[m]);
return 0;
}
//aabaaaab
作者:purplevine
出处:https://www.cnblogs.com/purplevine/p/16415986.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
本文来自博客园,作者:purplevine,转载请注明原文链接:https://www.cnblogs.com/purplevine/p/16415986.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下