UVa 1471 (LIS变形) Defense Lines

时间:2023-03-09 03:12:53
UVa 1471 (LIS变形) Defense Lines

题意:

给出一个序列,删掉它的一个连续子序列(该子序列可以为空),使得剩下的序列有最长的连续严格递增子序列。

分析:

这个可以看作lrj的《训练指南》P62中讲到的LIS的O(nlogn)的优化变形过来的问题。

预处理:

Li是第i个元素Ai向左延伸的最大长度,即[i, i + Li - 1]是一个递增区间

同样地,Ri是第i个元素向右延伸的最大长度。

我们,可以枚举i, j(j<i 且 Aj < Ai),这样就可以把Aj和Ai“拼接”起来,所得到的最长连续递增子列的长度就是Lj + Ri

继续优化:

对于某一个i,如果有La = Lb 且 Aa < Ab,则后一个状态一定不会比前一个状态更优,因为如果Ab和Ai能“拼接”上,Aa和Ai也一定能“拼接”上,所以只要保留Aa即可

所以,用一个数组g,gi记录向左延伸为i的最小的元素值。

用lower_bound找到gk ≥ Ai 的第一个下标,(k-1则是gk-1 < Ai 的最后一个下标),此时得到的最大长度为k-1+Ri

然后还要更新g的值,g[L[i]] = min(g[L[i]], A[i])

 #include <bits/stdc++.h>
using namespace std; const int maxn = + ;
const int INF = ; int a[maxn], L[maxn], R[maxn], g[maxn]; bool scan_d(int &ret)
{
char c;
if(c=getchar(),c==EOF) return ; //EOF
while(c!='-'&&(c<''||c>'')) c=getchar();
ret=(c=='-')?:(c-'');
while(c=getchar(),c>=''&&c<='') ret=ret*+(c-'');
return ;
} int main()
{
//freopen("in.txt", "r", stdin); int T;
scan_d(T);
while(T--)
{
int n;
scan_d(n);
for(int i = ; i < n; ++i) scan_d(a[i]);
R[n-] = ;
for(int i = n-; i >= ; --i) R[i] = (a[i] < a[i+]) ? (R[i+] + ) : ;
L[] = ;
for(int i = ; i < n; ++i) L[i] = (a[i] > a[i-]) ? (L[i-] + ) : ; int ans = ;
for(int i = ; i <= n; ++i) g[i] = INF;
for(int i = ; i < n; ++i)
{
int k = lower_bound(g+, g++n, a[i]) - g;
ans = max(ans, R[i] + k - );
if(a[i] < g[L[i]]) g[L[i]] = a[i];
}
printf("%d\n", ans);
} return ;
}

代码君