线性dp--最长上升子序列变形
A Twisty Movement
洛谷链接:https://www.luogu.com.cn/problem/CF933A
codeforce链接:https://codeforces.com/problemset/problem/933/A
题面翻译
给定一个序列 A,你可以翻转其中的一个区间内的数,求翻转后的序列的最长不下降子序列的长度。(
感谢@touristWang 提供的翻译
题目描述
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a
Little Tommy is among them. He would like to choose an interval
A non-decreasing subsequence is a sequence of indices
输入格式
The first line contains an integer
The second line contains
输出格式
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
样例 #1
样例输入 #1
4
1 2 1 2
样例输出 #1
4
样例 #2
样例输入 #2
10
1 1 2 2 2 1 1 2 2 1
样例输出 #2
9
提示
In the first example, after reversing
In the second example, after reversing
注意:解析扒的这位佬的 https://www.luogu.com.cn/article/fv3mhsdw
分析
考虑 DP
。
由于序列只有两个数,那么最终的非降子序列一定是
如果翻转后得到
因为最多交换一次,所以题目变成了找原序列的最长子序列,且形式为
一共有
-
,前 个部分:如果第
个数为 ,那么可以把这个数和以前的拼起来。答案为 。否则,如果第
个数为 ,那么这个数不可以作为第 部分。答案为 。因此
。 -
,前 个部分。如果第
个部分为空,那么答案为 。以下都是不空的情况。如果第
个数为 ,那么可以把这个数和以前的拼起来。答案为 。否则,如果第
个数为 ,那么这个数不可以作为第 部分。答案为 。因此
。 -
,前 个部分。如果第
个部分为空,那么答案为 。以下都是不空的情况。如果第
个数为 ,那么可以把这个数和以前的拼起来。答案为 。否则,如果第
个数为 ,那么这个数不可以作为第 部分。答案为 。因此
。 -
,前 个部分。如果第
个部分为空,那么答案为 。以下都是不空的情况。如果第
个数为 ,那么可以把这个数和以前的拼起来。答案为 。否则,如果第
个数为 ,那么这个数不可以作为第 部分。答案为 。因此
。
最后答案为
AC 代码:
#include <iostream>
using namespace std;
const int N = 2010;
int a[N];
int f[N][4];
int n;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++)
{
f[i][0] = f[i - 1][0] + (a[i] == 1);
f[i][1] = max(f[i][0], f[i - 1][1] + (a[i] == 2));
f[i][2] = max(f[i][1], f[i - 1][2] + (a[i] == 1));
f[i][3] = max(f[i][2], f[i - 1][3] + (a[i] == 2));
}
cout << f[n][3];
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具