题解:AT_arc149_b [ARC149B] Two LIS Sum
liujianchong · · 题解
ARC149 B 题解
Problem
给你两个
Solution
首先我们要证明一个事:那就是无论怎么操作,先把一个数组排好序再对另一个数组求 LIS 长度始终是最优的。
以下证明过程都是假设代码中对
我们取任意操作后的数组
,即
。
那么问题就转化为求 利用我们惊人的注意力发现,这
,所以
,证毕。
Implementation
先对 其实反过来不用了,但是我还是写了。
Code
AC Record
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int n;
struct node {
int a, b;
} s[N], t[N];
bool cmpa(node x, node y) {
return x.a < y.a;
}
bool cmpb(node x, node y) {
return x.b < y.b;
}
int lis[N];
// s: 备份数组,不动
// t: 实际数组,操作
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &s[i].a);
for (int i = 1; i <= n; i++)
scanf("%d", &s[i].b);
int ans = -1;
for (int i = 1; i <= n; i++)
t[i] = s[i];
sort(t + 1, t + 1 + n, cmpb);
memset(lis, 0, sizeof(lis));
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (i == 1 || t[i].a > lis[cnt]) {
lis[++cnt] = t[i].a;
}
else {
// upper_bound 返回第一个大于的
int pos = upper_bound(lis + 1, lis + 1 + cnt, t[i].a) - lis;
lis[pos] = t[i].a;
}
}
ans = max(ans, n + cnt);
for (int i = 1; i <= n; i++)
t[i] = s[i];
sort(t + 1, t + 1 + n, cmpa);
memset(lis, 0, sizeof(lis));
cnt = 0;
for (int i = 1; i <= n; i++) {
if (i == 1 || t[i].b > lis[cnt]) {
lis[++cnt] = t[i].b;
}
else {
// upper_bound 返回第一个大于的
int pos = upper_bound(lis + 1, lis + 1 + cnt, t[i].b) - lis;
lis[pos] = t[i].b;
}
}
ans = max(ans, n + cnt);
printf("%d", ans);
return 0;
}