微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在小背包实施中,我的解决方案始终使用相同的最大索引如何按降序对数组进行排序?

如何解决在小背包实施中,我的解决方案始终使用相同的最大索引如何按降序对数组进行排序?

import java.util.Scanner;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import static java.lang.Integer.min;

public class FractionalKnapsack {
  // this method for calculating the maximum index
 
  public static int select_max_index(int []values,int []weights,int n){

        int index=0;
        double max=0;

        for(int i=0;i<n;i++) {

            if (weights[i] > 0 && (double) values[i] / (double) weights[i] > max) {

                max = (double) values[i] / (double) weights[i];
                index = i;
            }
        }

        return index;
    }

    private static double getoptimalValue(int  capacity,int  [] values,int[] weights,int n) {

        // fractional knapsack problem
        int i;
        int max_index=0;
        double value = 0.0000d;
        if (capacity == 0)
            return value;
        for (i = 0; i < n; i++) {
            max_index = select_max_index(values,weights,n);// call the maximum index
            if (max_index >= 0) {
                int b = min(capacity,(weights[max_index]));
                value = value + b * ((double) values[max_index] / (double) weights[max_index]);
                weights[i] = (weights[max_index] - b);
                capacity = capacity - b;
            }
        }

        return value;
    }


    public static void main(String args[]) {
        Scanner scanner = new Scanner(system.in);
        int n = scanner.nextInt();
        int capacity = scanner.nextInt();
        int[] values = new int[n+2];
        int[] weights = new int[n+2];
        for (int i = 0; i < n; i++) {
            values[i] = scanner.nextInt();
            weights[i] = scanner.nextInt();
        }
        DecimalFormat df = new DecimalFormat(".0000"); // for getting the decimal point upto 4 digits
        df.setRoundingMode(RoundingMode.CEILING);
        System.out.println(df.format(getoptimalValue(capacity,values,n)));
    }
}

输入:

- 3 50
60 20
100 50
120 30

正确的输出

180.0000

我的输出

200.0

我的代码始终使用相同的最大索引。我是编程的初学者

解决方法

要使其正常工作,您需要进行以下更改:

  1. weights[i] = (weights[max_index] - b);更改为weights[max_index] = (weights[max_index] - b);,因为您正在修改max_index的权重,而不是其他项目的权重(索引错误)。
  2. index方法初始化select_max_index(从index=0index=-1)。没必要,但会很好,因此if (max_index >= 0)有意义。

您的算法的运行时间为O(n 2 )。最好根据小背包标准开始对所有项目进行排序的代码(以更大的value/weight为首)。您需要使用custom comparator。通过按这种顺序进行处理,时间复杂度将为O(n log n),这会更好。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。