建模成0-1背包问题,显示通过45%,超出内存限制
此处背包代码来自lanyu_01
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N = s.nextInt();//种类
int V = s.nextInt();//容量
// int[] weight = new int[N];
// for (int i = 0; i < N; i++) {
// weight[i] = 1;
// }
int[] value = new int[N];
for (int i = 0; i < N; i++) {
value[i] = s.nextInt() + 2 * s.nextInt();
}
String res = func(V, N, value);
System.out.println(res);
}
public static String func(int V,int N,int[] value){
int[][] dp = new int[N+1][V+1];
for(int i=1;i<N+1;i++){
for(int j=1;j<V+1;j++){
if(1 > j)
dp[i][j] = dp[i-1][j];
else
dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-1]+value[i-1]);
}
}
int maxValue = dp[N][V];
int j=V;
String numStr="";
for(int i=N;i>0;i--){
if(dp[i][j]>dp[i-1][j]){
numStr = i+(numStr.equals("") ? "" : " " + numStr);
j=j-1;
}
if(j==0)
break;
}
return numStr;
}
}
牛客网上java解答
作者:Rorke
链接:https://www.nowcoder.com/discuss/485697?type=post&order=time&pos=&page=1&channel=1013&source_id=search_post
来源:牛客网
package meituan;
import java.util.*;
/**
* @author Rorke
* @date 2020/8/22 16:23
*/
public class Q2 {
static class Order {
int v, w, orderNum, total;
public Order(int v, int w, int orderNum) {
this.v = v;
this.w = w;
this.orderNum = orderNum;
this.total = v + 2 * w;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt(), m = input.nextInt();
Queue<Order> queue = new PriorityQueue<>((o1, o2) -> o1.total == o2.total ? o1.orderNum - o2.orderNum : o2.total - o1.total);
for (int i = 0; i < n; i++) {
int v = input.nextInt(), w = input.nextInt();
queue.offer(new Order(v,w,i+1));
}
List<Integer> result = new ArrayList<>();
for (int i = 0; i < m; i++) {
result.add(queue.remove().orderNum);
}
result.sort(Comparator.comparingInt(i -> i));
result.forEach(i-> System.out.print(i+" "));
}
}