动态规划 NOIP经典问题 "开心的金明"(洛谷P1060题题解,Java语言描述)

题目要求

P1060题目链接

在这里插入图片描述

分析

经典的0/1背包问题,《背包九讲》中提到的典例。

动态转移方程: f [ j ] = M a t h . m a x ( f [ j ] , f [ j v [ i ] ] + w [ i ] ) f[j] = Math.max(f[j], f[j-v[i]]+w[i])

AC代码(Java语言描述)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] temp = reader.readLine().split("\\s+");
        int n = Integer.parseInt(temp[0]), m = Integer.parseInt(temp[1]);
        int[] v = new int[m], w = new int[m], f = new int[n+1];
        for (int i = 0; i < m; i++) {
            temp = reader.readLine().split("\\s+");
            v[i] = Integer.parseInt(temp[0]);
            w[i] = Integer.parseInt(temp[1])*v[i];
        }
        reader.close();
        for (int i = 0; i < m; i++) {
            for (int j = n; j >= v[i]; j--) {
                f[j] = Math.max(f[j], f[j-v[i]]+w[i]);
            }
        }
        System.out.println(f[n]);
    }
}
发布了717 篇原创文章 · 获赞 1513 · 访问量 69万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104850362