01 背包问题的另类解法

百度百科和大部分网站的解释背包问题,
http://baike.baidu.com/view/1731915.htm


感觉时间复杂度O(m*n);
刚好又别人解看到腾讯问题的文章:
http://baike.baidu.com/view/1731915.htm
感觉背包问题可以只是求最终结果的话,可以用权重来解决;
时间复杂度O(n);


用java编写的如下代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;




public class Backpack {




public static void main(String[] args) {
Backpack test = new Backpack();
List<Rely> relyList = new ArrayList<Rely>();
relyList.add(test.new Rely(1, 1));
relyList.add(test.new Rely(3, 3));
relyList.add(test.new Rely(5, 3));
relyList.add(test.new Rely(10, 3));
relyList.add(test.new Rely(6, 8));
relyList.add(test.new Rely(7, 5));
relyList = test.calcWeight(relyList);
for (Rely rely : relyList) {
System.out.println(rely);
}
System.out.println("Max: "+test.anyazer(6, relyList));




}




public int anyazer(int limit, List<Rely> relyList) {
int max = 0;
int remainder;
int mark = 0;
for (Rely rely : relyList) {
if (limit / rely.engry >= 1) {
max = limit / rely.engry * rely.happiness;
remainder = limit % rely.engry;
mark += max;
if (remainder != 0) {
limit = remainder;
continue;
}
break;
}
}
return mark;




}




public List<Rely> calcWeight(List<Rely> relyList) {
List<Rely> weightList = new ArrayList<Rely>();
for (Rely rely : relyList) {
Double weight = (double) rely.happiness / (double) rely.engry;
rely.setWeight(weight);
weightList.add(rely);
}
Collections.sort(weightList, Collections.reverseOrder());




return weightList;
}




public class Rely implements Comparable<Rely> {
private int happiness;
private int engry;
private double weight;




public Rely() {




}




public Rely(int happiness, int engry) {
this.happiness = happiness;
this.engry = engry;
}




public void setWeight(double weight) {
this.weight = weight;
}




public int getHappiness() {
return this.happiness;
}




public int getEngry() {
return this.engry;
}




@Override
public String toString() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(happiness).append("\t").append(engry)
.append("\t").append(weight);
return strBuilder.toString();
}




@Override
public int compareTo(Rely o) {
int flag;
flag = weight > o.weight ? 1 : (weight == o.weight ? 0 : -1);
if (flag == 0) {
flag = engry > o.engry ? 1 : (engry == o.engry ? 0 : -1);
}
return flag;
}




}




}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值