AcWing 896. 最长上升子序列 II-java
原题链接
中等
作者:
Astarion
,
2021-02-19 20:54:46
,
所有人可见
,
阅读 244
import java.io.*;
import java.util.Arrays;
class Main {
//存储长度为i的递增子序列最小的末尾值
static int[] dp = new int[100010];
//原序列
static int[] a = new int[100010];
//原序列长度
static int n;
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
strs = in.readLine().split(" ");
for (int i = 1; i <= n; i++) a[i] = Integer.parseInt(strs[i-1]);
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
Arrays.fill(dp,Integer.MAX_VALUE);
dp[0] = Integer.MIN_VALUE;
int len = 0;
for (int i = 1; i <= n; i++) {
//令r = len可缩小范围,且能解决初始化问题
int l = 0, r = len;
while (l < r) {
int mid = l + (r - l + 1)/2;
//二分判断极易出错(注意等于时的操作)
if (dp[mid] >= a[i]) r = mid - 1;
else l = mid;
}
dp[l + 1] = a[i];
len = Math.max(l + 1, len);
}
out.write(len + "");
out.flush();
out.close();
osw.close();
}
}