考试策略, 美团笔试题

典型01背包问题

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] p = new int[n];
        int[] a = new int[n];
        int[] q = new int[n];
        int[] b = new int[n];
        for(int i=0; i < n; i++) {
            p[i] =sc.nextInt(); a[i] = sc.nextInt();
            q[i] = sc.nextInt(); b[i] = sc.nextInt();
        }
        int[][] f = new int[n+1][121];
        for(int i=1; i <= n; i++) {
            for(int j=1; j <= 120; j++) {
                f[i][j] = f[i-1][j];
                if(j-p[i-1] >= 0) f[i][j] = Math.max(f[i][j], a[i-1] + f[i-1][j-p[i-1]]);
                if(j-q[i-1] >= 0) f[i][j] = Math.max(f[i][j], b[i-1] + f[i-1][j-q[i-1]]);
            }
        }
        System.out.println(f[n][120]);
    }
}

/*
01背包问题
f[i][j] 前i道题,花费时间为j,取得的最大分值。
f[i][j] = max(f[i-1][j], ai + f[i-1][j-pi], bi + f[j-qi])
*/

你可能感兴趣的:(考试策略, 美团笔试题)