Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

还是要用一维数组降低空间复杂度,不然很容易会出现Memory超限,加上自己的实现代码。

Posted by 201722362014068 at 2017-12-06 20:37:10 on Problem 3624
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:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator