这个是01背包,有一个小问题:用例中有些药是永远挖不到的。所以最后的结果不是在数组的最后一个位置,要特殊处理下
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(reader.readLine());
int T=Integer.parseInt(st.nextToken());//总共的时间
int M=Integer.parseInt(st.nextToken());//总共的药
Node1048[] nodes=new Node1048[M];
for (int i = 0; i <M ; i++) {
st=new StringTokenizer(reader.readLine());
int time=Integer.parseInt(st.nextToken());
int value=Integer.parseInt(st.nextToken());
nodes[i]=new Node1048(i,time,value);
}
Arrays.sort(nodes);
int[][] p=new int[T+1][M+1];
for (int i = 1; i <=T ; i++) {//时间
for (int j = 1; j <=M ; j++) {//每个药品
Node1048 node=nodes[j-1];
if(i>=node.time){//时间够了,才可以选择,挖还是不挖
int wa=node.value+p[i-node.time][j-1];
int nowa=p[i][j-1];
p[i][j]=Math.max(wa,nowa);
}
}
}
for (int i = M; i >=0 ; i--) {
if(p[T][i]!=0){
System.out.println(p[T][i]);
return;
}
}
reader.close();
}
}
class Node1048 implements Comparable<Node1048>{
int index;
int time;
public Node1048(int index, int time, int value) {
this.index = index;
this.time = time;
this.value = value;
}
int value;
@Override
public int compareTo(Node1048 o) {
return this.time-o.time;
}
}