Stanford Algorithms: Design and Analysis, Part 2[week 3]

Problem Set-3


dp[n][c1][c2]=max{dp[n-1][c1-w_n][c2]+v_n,dp[n-1][c1][c2-w_n]+v_n,dp[n-1][c1][c2]}
dp[n][c1][c2]表示两个背包现在分别有c1,c2的容量,取前n个物体的最大值
根据第n个物体由1,由2或者两人都不取来转移




Programming Assignment-3

Question 1

In this programming problem and the next you'll code up the knapsack algorithm from lecture. Let's start with a warm-up. Download the text file here. This file describes a knapsack instance, and it has the following format:
[knapsack_size][number_of_items]
[value_1] [weight_1]
[value_2] [weight_2]
...
For example, the third line of the file is "50074 659", indicating that the second item has value 50074 and size 659, respectively.

You can assume that all numbers are positive. You should assume that item weights and the knapsack capacity are integers.

In the box below, type in the value of the optimal solution.

ADVICE: If you're not getting the correct answer, try debugging your algorithm using some small test cases. And then post them to the discussion forum!

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

/*
 * Question 1
In this programming problem and the next you'll code up the knapsack algorithm from lecture. Let's start with a warm-up. Download the text file here. This file describes a knapsack instance, and it has the following format:
[knapsack_size][number_of_items]
[value_1] [weight_1]
[value_2] [weight_2]
...
For example, the third line of the file is "50074 659", indicating that the second item has value 50074 and size 659, respectively.
You can assume that all numbers are positive. You should assume that item weights and the knapsack capacity are integers.

In the box below, type in the value of the optimal solution.

ADVICE: If you're not getting the correct answer, try debugging your algorithm using some small test cases. And then post them to the discussion forum!
 */
public class PS3Q1 {
	static int numItems;
	static int W;//size of knapsack

	static class Item{
		int v; //value
		int w; //weight
		public Item(int v, int w){
			this.v= v;
			this.w = w;
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int A[][];

		Path p = Paths.get("knapsack1.txt");
		ArrayList<Item> items = new ArrayList<Item>();
		try {
			BufferedReader br = Files.newBufferedReader(p,StandardCharsets.UTF_8);
			String line = br.readLine();
			numItems = Integer.parseInt(line.split(" ")[1]);
			W = Integer.parseInt(line.split(" ")[0]);
			while ((line = br.readLine())!=null){
				int v = Integer.parseInt(line.split(" ")[0]);
				int w = Integer.parseInt(line.split(" ")[1]);
				items.add(new Item(v,w));
			}
			A = new int[numItems][W+1];
			for(int x =0;x<W+1;x++){
				A[0][x] = 0;				
			}
			for (int i =0;i<numItems;i++){
				for(int x =0;x<W+1;x++){
					int j = (i==0)?(0):(i-1);
					if (x<items.get(i).w){						
						A[i][x] = A[j][x];	
					}else{
						A[i][x] = Math.max(A[j][x], A[j][x-items.get(i).w]+items.get(i).v);
					}
				}
			}


			System.out.println("Answer :: "+A[numItems-1][W]);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

Question 2

This problem also asks you to solve a knapsack instance, but a much bigger one.

Download the text file here. This file describes a knapsack instance, and it has the following format:
[knapsack_size][number_of_items]
[value_1] [weight_1]
[value_2] [weight_2]
...
For example, the third line of the file is "50074 834558", indicating that the second item has value 50074 and size 834558, respectively. As before, you should assume that item weights and the knapsack capacity are integers.

This instance is so big that the straightforward iterative implemetation uses an infeasible amount of time and space. So you will have to be creative to compute an optimal solution. One idea is to go back to a recursive implementation, solving subproblems --- and, of course, caching the results to avoid redundant work --- only on an "as needed" basis. Also, be sure to think about appropriate data structures for storing and looking up solutions to subproblems.

In the box below, type in the value of the optimal solution.

ADVICE: If you're not getting the correct answer, try debugging your algorithm using some small test cases. And then post them to the discussion forum!

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

/*
 * Question 1
In this programming problem and the next you'll code up the knapsack algorithm from lecture. Let's start with a warm-up. Download the text file here. This file describes a knapsack instance, and it has the following format:
[knapsack_size][number_of_items]
[value_1] [weight_1]
[value_2] [weight_2]
...
For example, the third line of the file is "50074 659", indicating that the second item has value 50074 and size 659, respectively.
You can assume that all numbers are positive. You should assume that item weights and the knapsack capacity are integers.

In the box below, type in the value of the optimal solution.

ADVICE: If you're not getting the correct answer, try debugging your algorithm using some small test cases. And then post them to the discussion forum!
 */
public class PS3Q2 {
	static int numItems;
	static int W;//size of knapsack

	static class Item{
		int v; //value
		int w; //weight
		public Item(int v, int w){
			this.v= v;
			this.w = w;
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int A[][];

		Path p = Paths.get("knapsack2.txt");
		ArrayList<Item> items = new ArrayList<Item>();
		try {
			BufferedReader br = Files.newBufferedReader(p,StandardCharsets.UTF_8);
			String line = br.readLine();
			numItems = Integer.parseInt(line.split(" ")[1]);
			W = Integer.parseInt(line.split(" ")[0]);
			while ((line = br.readLine())!=null){
				int v = Integer.parseInt(line.split(" ")[0]);
				int w = Integer.parseInt(line.split(" ")[1]);
				items.add(new Item(v,w));
			}
			A = new int[2][W+1];
			for(int x =0;x<W+1;x++){
				A[0][x] = 0;				
			}
			for (int i =0;i<numItems;i++){
				for(int x =0;x<W+1;x++){
					int j = 0;
					if (x<items.get(i).w){						
						A[1][x] = A[j][x];	
					}else{
						A[1][x] = Math.max(A[j][x], A[j][x-items.get(i).w]+items.get(i).v);
					}
				}
				//copy A[1] to A[0]
				for(int k = 0; k<W+1;k++)
					A[0][k] = A[1][k];
			}


			System.out.println("Answer :: "+A[1][W]);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}



Harsh Bhasin, "Algorithms: Design and Analysis" English | ISBN: 0199456666 | 2015 | 692 pages Algorithms: Design and Analysis of is a textbook designed for the undergraduate and postgraduate students of computer science engineering, information technology, and computer applications. It helps the students to understand the fundamentals and applications of algorithms. The book has been divided into four sections: Algorithm Basics, Data Structures, Design Techniques and Advanced Topics. The first section explains the importance of algorithms, growth of functions, recursion and analysis of algorithms. The second section covers the data structures basics, trees, graphs, sorting in linear and quadratic time. Section three discusses the various design techniques namely, divide and conquer, greedy approach, dynamic approach, backtracking, branch and bound and randomized algorithms used for solving problems in separate chapters. The fourth section includes the advanced topics such as transform and conquer, decrease and conquer, number thoeretics, string matching, computational geometry, complexity classes, approximation algorithms, and parallel algorithms. Finally, the applications of algorithms in Machine Learning and Computational Biology areas are dealt with in the subsequent chapters. This section will be useful for those interested in advanced courses in algorithms. The book also has 10 appendixes which include topics like probability, matrix operations, Red-black tress, linear programming, DFT, scheduling, a reprise of sorting, searching and amortized analysis and problems based on writing algorithms. The concepts and algorithms in the book are explained with the help of examples which are solved using one or more methods for better understanding. The book includes variety of chapter-end pedagogical features such as point-wise summary, glossary, multiple choice questions with answers, review questions, application-based exercises to help readers test their understanding of the learnt concepts.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值