当前位置:网站首页>AcWing 272. 最长公共上升子序列
AcWing 272. 最长公共上升子序列
2022-08-11 07:35:00 【超级码力奥】
原题连接:https://www.acwing.com/problem/content/description/274/
谁能想到这么表示状态???
优化
/* 状态表示: f[i][j]代表所有a[1 ~ i]和b[1 ~ j]中以b[j]结尾的公共上升子序列的集合; f[i][j]的值等于该集合的子序列中长度的最大值; 状态计算(对应集合划分): 首先依据公共子序列中是否包含a[i],将f[i][j]所代表的集合划分成两个不重不漏的子集: 不包含a[i]的子集,最大值是f[i - 1][j]; 包含a[i]的子集,将这个子集继续划分,依据是子序列的倒数第二个元素在b[]中是哪个数: 子序列只包含b[j]一个数,长度是1; 子序列的倒数第二个数是b[1]的集合,最大长度是f[i - 1][1] + 1; … 子序列的倒数第二个数是b[j - 1]的集合,最大长度是f[i - 1][j - 1] + 1; 边界: 初始化: f[0][1...n] = 0, f[1...n][0] = 0; 答案: max(f[n][1...n]) */
#include <iostream>
using namespace std;
const int N = 3010;
int n;
int a[N], b[N];
int f[N][N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
for (int i = 1; i <= n; i ++ ) scanf("%d", &b[i]);
// 这个最内层循环可以优化一下
// for (int i = 1; i <= n; i ++)
// for (int j = 1; j <= n; j ++ )
// {
// //a[i] != b[j]
// f[i][j] = f[i - 1][j];
// // a[i] = b[j]
// if(a[i] == b[j])
// {
// int maxv = 1;
// for (int k = 1; k <= j - 1; k ++ )
// if (b[k] < b[j])
// maxv = max(maxv, f[i - 1][k] + 1);
// f[i][j] = max(maxv, f[i][j]);
// }
// }
for (int i = 1; i <= n; i ++)
{
// 额,确实可以这样优化,因为只有b[j] = a[i]的时候,
// f[i][j]才会变大,此时,用maxv就行了,maxv代表前缀上升子序列最大长度
// 这里的maxv就变味了。和上边的意思不一样了。
int maxv = 1;
for (int j = 1; j <= n; ++ j)
{
f[i][j] = f[i - 1][j];
if (b[j] == a[i]) f[i][j] = max(f[i][j], maxv);
if (b[j] < a[i]) maxv = max(maxv, f[i - 1][j] + 1);
}
}
int res = 0;
// 为啥结果是枚举b[i], 因为你看状态定义,不能枚举a[i]
// 按照状态定义,不一定b[n]一定取到,但是a[n]是肯定的
for(int i = 1; i <= n; i ++) res = max(res, f[n][i]);
cout << res << endl;
return 0;
}
边栏推荐
猜你喜欢
About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display
1101 How many times B is A (15 points)
1051 复数乘法 (15 分)
FPGA 20个例程篇:11.USB2.0接收并回复CRC16位校验
1036 Programming with Obama (15 points)
查找最新人员工资和上上次人员工资的变动情况
数仓开发知识总结
CSDN21天学习挑战赛——封装(06)
JUC并发编程
3.1-Classification-probabilistic generative model
随机推荐
go-grpc TSL认证 解决 transport: authentication handshake failed: x509 certificate relies on ... ...
Redis source code-String: Redis String command, Redis String storage principle, three encoding types of Redis string, Redis String SDS source code analysis, Redis String application scenarios
Four startup modes of Activity
string类接口介绍及应用
cdc连sqlserver异常对象可能有无法序列化的字段 有没有大佬看得懂的 帮忙解答一下
TF中的One-hot
【Day_13 0509】▲跳石板
经典论文-MobileNet V1论文及实践
机器学习总结(二)
4.1 - Support Vector Machines
【415. 字符串相加】
Service的两种启动方式与区别
Active users of mobile banking grew rapidly in June, hitting a half-year high
The growth path of a 40W test engineer with an annual salary, which stage are you in?
tf.cast(),reduce_min(),reduce_max()
TF generates (feature, label) set through feature and label, tf.data.Dataset.from_tensor_slices
查找最新人员工资和上上次人员工资的变动情况
为什么会没有内存了呢
【TA-霜狼_may-《百人计划》】图形3.7.2 command buffer简
Distributed Lock-Redission - Cache Consistency Solution