闲来无事敲的几行代码,贪心算法的核心在于先排序,找到一种规律,然后根据问题要求遍历列表解决问题.

贴出代码:

package 背包问题贪心算法;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;


public class Main {


public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int testnum=input.nextInt();
for (int i = 0; i < testnum; i++)
{
int goodsNum=input.nextInt();
int bagContain=input.nextInt();
ArrayList<Goods> goodsList=new ArrayList<Goods>();
for(int j=0;j<goodsNum;j++)
{
Goods goods=new Goods();
goods.value=input.nextInt();
goods.weight=input.nextInt();
goodsList.add(goods);
}
Collections.sort(goodsList);
int bagValue=0;
for(int k=0;k<goodsList.size();k++)
{
if (bagContain!=0) {
if (bagContain-goodsList.get(k).weight>0) {
bagContain-=goodsList.get(k).weight;
bagValue+=goodsList.get(k).value*goodsList.get(k).weight;
}
else if (bagContain-goodsList.get(k).weight<=0) {
bagValue+=goodsList.get(k).value*bagContain;
bagContain=0;
}
}
}
System.out.println(bagValue);
}
input.close();
}

public static class Goods implements Comparable<Goods>
{
public int value;
public int weight;
@Override
public int compareTo(Goods o) {

if (this.value>o.value) {
return -1;
}
else if (this.value==o.value) {
return 0;
} 
else {
return 1;
}
}

}
}
12-06 05:26