洛谷java实现(P1091合唱队形)

题目连接:https://www.luogu.com.cn/problem/P1091

这题和导弹拦截特别像,本质都是求最长上升子序列。

import java.util.Scanner;
/**
 * 贪心优化-时间复杂度 :O(nlogn)
 */
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] datas = new int[n];
        for (int i = 0; i < n; i++) {
            datas[i] = in.nextInt();
        }
        int len = 0;
        int[] top = new int[n];
        int[] increase = new int[n];
        for (int i = 0; i < n; i++) {//求1—n到的最长上升
            int data = datas[i];
            int begin = 0, end = len;
            while (begin < end) {
                int mid = (begin + end) >> 1;
                if (data <= top[mid]) {//严格递增
                    end = mid;
                } else {
                    begin = mid + 1;
                }
            }
            top[begin] = data;
            if (begin == len) {
                len++;
            }
            increase[i] = len;
        }
        len = 0;
        int[] top2 = new int[n];
        int[] decrease = new int[n];
        for (int i = n - 1; i >= 0; i--) {//求n-1到的最长上升
            int data = datas[i];
            int begin = 0, end = len;
            while (begin < end) {
                int mid = (begin + end) >> 1;
                if (data <= top2[mid]) {//严格递增
                    end = mid;
                } else {
                    begin = mid + 1;
                }
            }
            top2[begin] = data;
            if (begin == len) {
                len++;
            }
            decrease[i] = len;
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans = Math.max(ans, increase[i] + decrease[i] - 1);//最终相遇时的最大数是必定同一个数,减掉重复计算的最大数
        }
        System.out.println(n - ans);
    }
}
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页