【Java】背包问题

package org.wjp;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wujunpei
 */
public class Main {
    public static void main(String[] args) {
        List<Thing> things = new ArrayList<>();
        int maxWeight = 6;
        things.add(new Thing("水", 3, 10));
        things.add(new Thing("书", 1, 3));
        things.add(new Thing("食物", 2, 9));
        things.add(new Thing("夹克", 2, 5));
        things.add(new Thing("相机", 1, 6));
        int[][] array = new int[things.size()][maxWeight];
        String[][] whatThings = new String[things.size()][maxWeight];
        for (int i = 0; i < things.size(); i++) {
            Thing nowThing = things.get(i);
            for (int j = 0; j < maxWeight; j++) {
                int nowValue = nowThing.weight <= (j + 1) ? nowThing.value : 0;
                int nowWeight = nowThing.weight <= (j + 1) ? nowThing.weight : 0;
                int restValue = (i < 1 || j - nowWeight < 0) ? 0 : array[i - 1][j - nowWeight];
                String restName = (i < 1 || j - nowWeight < 0) ? "" : whatThings[i - 1][j - nowWeight];
                int nowWeightValueWithoutNowThing = i < 1 ? 0 : array[i - 1][j];
                String nowNameValueWithoutNowThing = i < 1 ? "" : whatThings[i - 1][j];
                if (nowWeightValueWithoutNowThing >= nowValue + restValue) {
                    array[i][j] = nowWeightValueWithoutNowThing;
                    whatThings[i][j] = nowNameValueWithoutNowThing;
                } else {
                    array[i][j] = nowValue + restValue;
                    whatThings[i][j] = nowThing.name + ("".equals(restName) ? "" : "、" + restName);
                }

            }
        }
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.printf("%4d", array[i][j]);
            }
            System.out.println();
        }
        for (int i = 0; i < whatThings.length; i++) {
            for (int j = 0; j < whatThings[i].length; j++) {
                System.out.printf("\t%s\t", whatThings[i][j].equals("") ? "无" : whatThings[i][j]);
            }
            System.out.println();
        }
    }

    static class Thing {
        String name;
        int weight;
        int value;

        public Thing(String name, int weight, int value) {
            this.name = name;
            this.weight = weight;
            this.value = value;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值