本文主要是介绍POJ1384背包,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
体积V的包包
n种硬币,体积weight价值value
求把包包恰好装满最小的价值
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;public class Main {public static void main(String[] args) {new Task().sovle();}
}class Task {InputReader in = new InputReader(System.in);PrintWriter out = new PrintWriter(System.out);void sovle() {int t = in.nextInt() ;while(t-- > 0){int V = -in.nextInt() + in.nextInt() ;int n = in.nextInt() ;dp = new int[V+1] ;weight = new int[n+1] ;value = new int[n+1] ;for(int i = 1 ; i <= n ; i++){value[i] = in.nextInt() ;weight[i] = in.nextInt() ;}Arrays.fill(dp , inf) ;dp[0] = 0 ;for(int i = 1 ; i <= n ; i++){for(int v = weight[i] ; v <= V ; v++){if(dp[v - weight[i]] != inf)dp[v] = Math.min(dp[v] , value[i] + dp[v - weight[i]]) ;}}if(dp[V] == inf) out.println("This is impossible.") ;else out.println("The minimum amount of money in the piggy-bank is " + dp[V] + ".") ;}out.flush() ;}int[] dp , weight , value ;final int inf = 1000000000 ;}class InputReader {public BufferedReader reader;public StringTokenizer tokenizer;public InputReader(InputStream stream) {reader = new BufferedReader(new InputStreamReader(stream), 32768);tokenizer = new StringTokenizer("");}private void eat(String s) {tokenizer = new StringTokenizer(s);}public String nextLine() {try {return reader.readLine();} catch (Exception e) {return null;}}public boolean hasNext() {while (!tokenizer.hasMoreTokens()) {String s = nextLine();if (s == null)return false;eat(s);}return true;}public String next() {hasNext();return tokenizer.nextToken();}public int nextInt() {return Integer.parseInt(next());}public long nextLong() {return Long.parseLong(next());}public double nextDouble() {return Double.parseDouble(next());}public BigInteger nextBigInteger() {return new BigInteger(next());}}
这篇关于POJ1384背包的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!