Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
还是要用一维数组降低空间复杂度,不然很容易会出现Memory超限,加上自己的实现代码。import java.util.*; public class poj3624{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n =in.nextInt(); int m =in.nextInt(); //w数组保存每个物品的重量 int[] w = new int[n+1]; //v数组保存每个物品的价值 int[] v = new int[n+1]; for(int i=1;i<=n;i++) { w[i]=in.nextInt(); v[i]=in.nextInt(); } System.out.println(result(w,v,n,m)); } public static int result(int[] w,int[] v,int n,int m) { //f数组中f[i]保存给定背包i容量下,n个物品中可以放入的最大价值 int[] f = new int[m+1]; for(int i=1;i<=n;i++) { for(int j=m;j>=w[i];j--) {//和二维数组实现动态规划不同,j区间是逆着走{w[i],m} f[j]=Math.max(f[j-w[i]]+v[i], f[j]); } } return f[m]; } } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator