时间复杂度
O(n^2)
换成单调栈
O(nlogn)
算法思想
一岸从小到大排序,另一岸求最长上升子序列,这样连线就互不相交
java 代码
//一岸从小到大排序,另一岸求最长上升子序列
import java.util.*;
class Main{
static int n = 0, N = 5010;
static int[][] nums = new int[N][2];
static int[] max = new int[N];
public static void main(String[] args)throws Exception{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for(int i = 1; i <= n; ++i){
nums[i][0] = sc.nextInt();
nums[i][1] = sc.nextInt();
}
Arrays.sort(nums, 1, n + 1, (a, b) -> a[0] - b[0]);
int res = 0;
for(int i = 1; i <= n; ++i){
max[i] = 1;
for(int j = 1; j <= i; ++j){
if(nums[i][1] > nums[j][1])
max[i] = Math.max(max[i], max[j] + 1);
res = Math.max(res, max[i]);
}
}
System.out.print(res);
}
}