Longest subsequence
String is a very useful thing and a subsequence of the same string is equally important.
Now you have a string ss with length nn and a string tt with length mm. Find out the longest subsequence in the string ss so that the lexicographical order of this subsequence is strictly larger than tt.
Input
two integers nn, mm in the first line
(All characters are lowercase letters)
The second line is a string ss
The third line is a string tt
- 1 \le n,m \le 10^61≤n,m≤106
Output
Output an integer representing the longest length, otherwise output -1
.
样例输入1
9 3 aaabbbccc abc
样例输出1
6
样例输入2
9 3 aaabbbccc zzz
样例输出2
-1
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=1e6+10; int n,m; char s[maxn],t[maxn]; int nx[maxn][26]; int main() { scanf("%d%d",&n,&m); scanf("%s%s",s+1,t+1); for(register int i=0;i<26;++i){ nx[n][i]=nx[n+1][i]=n+1; } for(register int i=n-1;i>=0;--i){ for(register int j=0;j<26;++j){ nx[i][j]=nx[i+1][j]; } int to=s[i+1]-'a'; nx[i][to]=i+1; } int res=-1,cur=0; for(register int i=1;t[i];++i){ int pos=t[i]-'a'; for(register int j=pos+1;j<26;++j){ int id=nx[cur][j]; if(id<=n){ res=max(res,n-id+1+i-1); } } cur=nx[cur][pos]; if(cur>n)break; } if(cur<n)res=max(res,m+n-cur); printf("%d\n",res); return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!