普及练习场 线性动态规划 合唱队形

题目链接

题意理解

这道题目数据范围非常小,所以是可以使用 O(n2) 算法的。直接正着DP再反着DP,最后求和减一,得到最大的值就是最后留下来的人数。

代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    static int N;
    static final int maxn = 110;
    static int[] a = new int[maxn];
    static int[] dp1 = new int[maxn];
    static int[] dp2 = new int[maxn];
    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        N = fs.nextInt();
        for(int i = 1; i <= N; i++) {
            a[i] = fs.nextInt();
        }
        dp1[1] = 0;
        for(int i = 1; i <= N; i++) {
            for(int j = 0; j < i; j++) {
                if(a[i] > a[j]) {
                    dp1[i] = Math.max(dp1[i], dp1[j] + 1);
                }
            }
        }
        dp2[N] = 0;
        for(int i = N; i >= 1; i--) {
            for(int j = N + 1; j > i; j--) {
                if(a[i] > a[j]) {
                    dp2[i] = Math.max(dp2[i], dp2[j] + 1);
                }
            }
        }
        int max = -1;
        for(int i = 1; i <= N; i++) {
            if(dp1[i] + dp2[i] - 1> max) {
                max = dp1[i] + dp2[i] - 1;
            }
        }
        System.out.println(N - max);

    }

    public static class FastScanner {
        private BufferedReader br;
        private StringTokenizer st;

        public FastScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public String nextToken() {
            while(st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.valueOf(nextToken());
        }
    }
}

你可能感兴趣的:(洛谷,洛谷从零单刷)