


package hwod;
import java.util.*;
public class LargestReliability {
private static int ans = -1;//最终结果
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int totalPrice = sc.nextInt(); //预算
int targetNum = sc.nextInt();//需要的元器件种类
int total = sc.nextInt(); //总共的元器件数量
sc.nextLine();
Device[] devices = new Device[total];
for (int i = 0; i < total; i++) {
String[] lines = sc.nextLine().split(" ");
Device device = new Device(Integer.parseInt(lines[0]), Integer.parseInt(lines[2]), Integer.parseInt(lines[1]));
devices[i] = device;
}
System.out.println(largestReliability(devices, totalPrice, targetNum));
}
//从devices中选择targetNum种元器件,价格不超过totalPrice,能够得到的最高可靠性是多少?
private static int largestReliability(Device[] device, int totalPrice, int targetNum) {
//从total里面选取target
LinkedList<Device> path = new LinkedList<>();//组合问题,临时选到path中去
int[] used = new int[targetNum];
dfs(device, 0, path, used, totalPrice, targetNum, Integer.MAX_VALUE);
return ans;
}
private static void dfs(Device[] devices, int begin, LinkedList<Device> path, int[] used, int totalPrice, int targetNum, int reliability) {
if (path.size() == targetNum) {
if (totalPrice >= 0 && reliability > ans) {
ans = reliability;
}
return;
}
for (int i = begin; i < devices.length; i++) {
if (used[devices[i].getType()] == 1) continue;//剪枝,不能选择同类型的type
path.addLast(devices[i]);
used[devices[i].getType()] = 1;
dfs(devices, i + 1, path, used, totalPrice - devices[i].getPrice(), targetNum, Math.min(reliability, devices[i].getReliability()));
path.removeLast();
used[devices[i].getType()] = 0;
}
}
}
class Device {
private int type;
private int price;
private int reliability;
public Device(int type, int price, int reliability) {
this.type = type;
this.price = price;
this.reliability = reliability;
}
public int getType() {
return type;
}
public int getPrice() {
return price;
}
public int getReliability() {
return reliability;
}
}
&spm=1001.2101.3001.5002&articleId=148678501&d=1&t=3&u=1ef40dda759147b1b67cfa0bebed8be3)

被折叠的 条评论
为什么被折叠?



