当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

Redis source code: how to view the Redis source code, the order of viewing the Redis source code, the sequence of the source code from the external data structure of Redis to the internal data structu

关于#sql#的问题:怎么将下面的数据按逗号分隔成多行,以列的形式展示出来

tf.cast(), reduce_min(), reduce_max()

1101 How many times B is A (15 points)

少年成就黑客,需要这些技能

oracle数据库中列转行,列会有变化

Square, multi-power, square root calculation in Tf
4.1-支持向量机
1.1-回归

查找最新人员工资和上上次人员工资的变动情况
随机推荐
伦敦银规则有哪些?
go sqlx 包
1071 Small Gamble (15 points)
1046 punches (15 points)
1091 N-自守数 (15 分)
Redis source code: how to view the Redis source code, the order of viewing the Redis source code, the sequence of the source code from the external data structure of Redis to the internal data structu
tf中自减操作;tf.assign_sub()
2022年中国软饮料市场洞察
Square, multi-power, square root calculation in Tf
Find the latest staff salary and the last staff salary changes
无服务器+域名也能搭建个人博客?真的,而且很快
线程交替输出(你能想出几种方法)
数仓开发知识总结
Pico neo3 Unity Packaging Settings
tf.reduce_mean()与tf.reduce_sum()
【415. 字符串相加】
go-grpc TSL认证 解决 transport: authentication handshake failed: x509 certificate relies on ... ...
Activity的四种启动模式
【Pytorch】nn.PixelShuffle
动态代理学习