4418. 选元素

    思路:
    DP
    f[i][j]表示从前i个元素中选j个且第i个元素被选的最大元素和
    初始化:f[i][j] = -1e15, f[0][0] = 0
    状态转移:
    因为题目要求每k个元素一定有一个被选,故第i个元素被选,上一个被选的一定是p ∈Math.max(0, i - k), i - 1范围内
    f[i][j] = Math.max(f[i][j], f[p][j - 1] + a[i]
    结果:
    最后一个被选元素一定位于最后k个元素中,遍历找最大值

    1. import java.util.*;
    2. public class Main {
    3. static final int N = 211;
    4. static int[] a = new int[N];
    5. static long[][] f = new long[N][N];
    6. static int n, k, m;
    7. public static void main(String[] args) {
    8. Scanner sc = new Scanner(System.in);
    9. n = sc.nextInt();
    10. k = sc.nextInt();
    11. m = sc.nextInt();
    12. for (int i = 1; i <= n; i++)
    13. a[i] = sc.nextInt();
    14. for (int i = 0; i <= n; i++)
    15. Arrays.fill(f[i], (long)(-1e15));
    16. f[0][0] = 0;
    17. for (int i = 1; i <= n; i++) {
    18. for (int j = 1; j <= Math.min(i, m); j++) {
    19. for (int p = Math.max(0, i - k); p < i; p++)
    20. f[i][j] = Math.max(f[i][j], f[p][j - 1] + a[i]);
    21. }
    22. }
    23. long ans = -1;
    24. for (int i = Math.max(1, n - k + 1); i <= n; i++)
    25. ans = Math.max(ans, f[i][m]);
    26. System.out.println(ans);
    27. }
    28. }