动态规划之背包入门01背包模板

P2925 [USACO08DEC] Hay For Sale S - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

采用一维数组优化,倒序遍历保证每件物品只会被加入背包一次。




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.PublicKey;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.TreeSet;
import java.util.function.IntPredicate;

import javax.print.attribute.standard.JobMessageFromOperator;

public class Main{
    public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
value=new int[b+3];
dp=new int[a+3];
weight=new int[b+3];
int c,d,e,f;
for(c=1;c<=b;c++) {
weight[c]=sc.nextInt();

}
for(c=1;c<=b;c++) {
	for(d=a;d>=weight[c];d--) {
		dp[d]=Math.max(dp[d], dp[d-weight[c]]+weight[c]);
	}
}
System.out.println(dp[a]);
    }
  public static int[] value;
  public static int[] dp;
  public static int[] weight;
    }

你可能感兴趣的:(算法模板,动态规划,算法,java)