给定重量上限,背包问题_满足给定重量的袋子的最低成本

给定重量上限,背包问题

Problem statement:

问题陈述:

You are given a bag of size W kg and you are provided costs of packets different weights of oranges in array cost[] where cost[i] is basically cost of i kg packet of oranges. cost[i] = -1 means that i kg packet of orange is unavailable.

给您一个大小为W kg的袋子,并为您提供数组cost []中重量不同的橙子的包装成本,其中cost [i]基本上是i kg橙子包装的成本。 cost [i] = -1表示i kg包橙色不可用。

Find the minimum total cost to buy exactly W kg oranges and if it is not possible to buy exactly W kg oranges then print -1. It may be assumed that there is infinite supply of all available packet types.

找到购买正好为W千克橘子的最低总成本,如果不可能购买正好为W千克橘子,则打印-1 。 可以假定存在所有可用分组类型的无限供应。

Input:

输入:

The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains integers N and W where N denotes the size of array cost[ ] and W is the size of the bag.

输入的第一行包含一个整数T,表示测试用例的数量。 然后是T测试用例。 每个测试用例的第一行包含整数NW ,其中N表示数组cost []的大小, W表示袋子的大小。

The second line of each test case contains N space separated integers denoting elements of the array cost[ ].

每个测试用例的第二行包含N个由空格分隔的整数,它们表示数组cost []的元素。

Output:

输出:

Print the minimum cost to buy exactly W kg oranges. If no such answer exists print "-1".

打印最低成本以购买正好为W公斤的橘子。 如果不存在这样的答案,请打印“ -1”

Constraints:

限制条件:

1 <= T <= 100
1 <= N, W <= 1000
1 <= cost[] <= 1000 

Example:

例:

Input:
2
5 5
20 10 4 50 100
6 5
-1 -1 4 5 -1 -1
Output:
14
-1

Explanation:

说明:

So, for the first test case,
The 1 kg orange packet costs: 20
The 2 kg orange packet costs: 10
The 3 kg orange packet costs: 4
The 4 kg orange packet costs: 50
The 5 kg orange packet costs: 100
We need total of 5 Kg orange
So, there are many options to pick orange packets
Like picking five 1 kg packets costing 100
two 2 kg and one 1kg packet costing 40
one 2kg and one 3kg packet costing 14
one 1kg and one 4kg costing 70
one 5kg costing 100
so minimum cost one would be one 2kg and 
one 3kg bag combination which costs 14
For the second test case,
There is no possible combination to sum total 5kg oranges
Since, only available weight packets are of 3kg and 4kg
We can't take fractional parts
So, it's not possible and answer is -1.

Solution approach

解决方法

This is kind of a duplicate knapsack problem with some constraints. Here we need to keep the check for available packets too.

这是一个重复的背包问题,但有一些约束。 在这里,我们还需要检查可用数据包。

For example,

例如,

Say we have total weights 8

假设我们有总重量8

kg and for an instance, we are checking with packet weight 5

公斤,例如,我们正在检查包装重量5

In such a case, we need to check to things.

在这种情况下,我们需要检查一下事情。

  1. Whether the 5kg packet is available or not.

    5公斤小包是否可用。

  2. Whether the sub-problem of size (8-5) kg is already solved or not.

    (8-5)kg大小的子问题是否已解决。

If both satisfies then only we can proceed with this instance to compute the current problem.

如果两个都满足,则只有我们可以继续进行本实例计算当前问题。

The above concepts lead to the recurring formula which can be easily converted to Dynamic Programming like below,

上面的概念导致了重复出现的公式,可以很容易地将其转换为动态编程,如下所示,

  1. Initialize dp[w+1] with INT_MAX where w is the total weight which is to be computed;

    用INT_MAX初始化dp [w + 1],其中w是要计算的总权重;

  2. Set dp[0]=0 as base case,

    将dp [0] = 0设置为基本情况,

  3. for(int i=1;i<=w;i++)
    for(int j=0;j<n;j++)
    if ( a[j]  is availble  && (j+1)<=i && dp[i-(j+1)]  is already computed && dp[i-(j+1)]+a[j]<dp[i])
    dp[i]=dp[i-(j+1)]+a[j];
    end if
    end for
    end for
    
    
  4. if(dp[w]  is not computed over the process,contains still the initial value)
    return -1;
    else dp[w] is the minimum cost
    
    

C++ Implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;
int minimumCost(vector<int> a, int n, int w)
{
int dp[w + 1];
dp[0] = 0;
for (int i = 1; i <= w; i++)
dp[i] = INT_MAX;
for (int i = 1; i <= w; i++) {
for (int j = 0; j < n; j++) {
if (a[j] != -1 && (j + 1) <= i && dp[i - (j + 1)] != INT_MAX && dp[i - (j + 1)] + a[j] < dp[i]) {
dp[i] = dp[i - (j + 1)] + a[j];
}
}
}
if (dp[w] == INT_MAX)
return -1;
return dp[w];
}
int main()
{
int t, n, item, w;
cout << "Enter number of test cases\n";
cin >> t;
for (int i = 0; i < t; i++) {
cout << "Enter number of elements\n";
cin >> n;
cout << "Enter total weight\n";
cin >> w;
cout << "Enter the cost of weights, -1 if not available\n";
vector<int> a;
for (int j = 0; j < n; j++) {
scanf("%d", &item);
a.push_back(item);
}
cout << "minimum cost is: " << minimumCost(a, n, w) << endl;
}
return 0;
}

Output:

输出:

Enter number of test cases
2
Enter number of elements
5 
Enter total weight
5
Enter the cost of weights, -1 if not available
20 10 4 50 100
minimum cost is: 14
Enter number of elements
6
Enter total weight
5
Enter the cost of weights, -1 if not available
-1 -1 4 5 -1 -1
minimum cost is: -1

翻译自: https://www.includehelp.com/icp/minimum-cost-to-fill-given-weight-in-a-bag.aspx

给定重量上限,背包问题

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/541445.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

springMVC rest风格

1.dispatcherServlet的配置<!-- The front controller of this Spring Web application, responsible for handling all application requests --><servlet><servlet-name>springDispatcherServlet</servlet-name><servlet-class>org.springfram…

sql2008能否打开mysql数据库_mysql数据库数据能不能导入到sql server中

点“测试”按钮确认你的链接是正确的。 Press the "Test" button to ensure your connection settings are set properly and then the "OK" button when youre done.二. 创建Microsoft SQL到MySQL的链接1.在SQL Server Management Studio中打开一个new qu…

c语言 函数的参数传递示例_isunordered()函数与C ++中的示例

c语言 函数的参数传递示例C isunordered()函数 (C isunordered() function) isunordered() function is a library function of cmath header, it is used to check whether the given values are unordered (if one or both values are Not-A-Number (NaN)), then they are u…

java进一_JAVA小白进:基础入门知识

1.注释&#xff0c;关键字&#xff0c;标识符1.注释(1)注释&#xff1a;解释说明程序的而文字。(2)注释的分类&#xff1a;单行注释 格式&#xff1a; //注释的文字多行注释 格式&#xff1a;/*注释的文字*/文档注释 格式&#xff1a;/**注释的文字*/(3)注释的作用&#xff1a;…

补丁(patch)的制作与应用

为什么80%的码农都做不了架构师&#xff1f;>>> 转自http://linux-wiki.cn/wiki/zh-hans/%E8%A1%A5%E4%B8%81(patch)%E7%9A%84%E5%88%B6%E4%BD%9C%E4%B8%8E%E5%BA%94%E7%94%A8 如果hack了开源代码&#xff0c;为了方便分享&#xff08;如提交Bug&#xff09;或自己…

php知识点汇总与解答_PHP操作员能力倾向问题与解答

php知识点汇总与解答This section contains Aptitude Questions and Answers on PHP Operators. 本节包含有关PHP运算符的 Aptitude问答。 1) Which of the following types of operators are used in PHP? Arithmetic OperatorsLogical OperatorsArray OperatorsString Oper…

csv导入mysql phpmyadmin_【转】从phpMyAdmin批量导入Excel内容到MySQL(亲测非常简洁有效)...

今天做项目遇到需要用phpMyAdmin批量导入Excel内容到MySQL数据库。分析了我的踏坑经历并且总结一最便捷的一套导入数据的方法&#xff0c;非常实用简洁&#xff1a;1、修改Excel表的数据&#xff0c;使得Excel中的字段与数据库字段要一一对应&#xff0c;并加上自增id。2、然后…

weakhashmap_Java WeakHashMap putAll()方法与示例

weakhashmapWeakHashMap类的putAll()方法 (WeakHashMap Class putAll() method) putAll() method is available in java.util package. putAll()方法在java.util包中可用。 putAll() method is used to copy all of the associations or mappings from the given map and assig…

c语言memcmp和java的_C语言memcmp()函数:比较m字节长的两个字符串s1和s2

函数名&#xff1a;memcmp头文件&#xff1a;函数原型&#xff1a; void* memcmp(void *s1,void *s2,unsigned m);功能&#xff1a;比较m字节长的两个字符串s1和s2参数&#xff1a; s1 和 s2 为要比较的字符串unsigned m 为要比较的前m个字节返回值&#xff1a;s1s1s2 返回等…

[下载地址] Subclipse 1.10.9(SVN) _附说明

http://pan.baidu.com/s/1bp6EFHt转载于:https://www.cnblogs.com/gscq073240/articles/6814429.html

hbase 伪分布安装 java_HBase基础和伪分布式安装配置

一、HBase(NoSQL)的数据模型1.1 表(table)&#xff0c;是存储管理数据的。1.2 行键(row key)&#xff0c;类似于MySQL中的主键&#xff0c;行键是HBase表天然自带的&#xff0c;创建表时不需要指定1.3 列族(column family)&#xff0c;列的集合。一张表中有多个行健&#xff0c…

java treemap_Java TreeMap firstEntry()方法及示例

java treemapTreeMap类的firstEntry()方法 (TreeMap Class firstEntry() method) firstEntry() method is available in java.util package. firstEntry()方法在java.util包中可用。 firstEntry() method is used to retrieve the key-value pairs linked with the lowest valu…

linux常用网络命令ping和arping

linux常用网络命令ping和arping ping 向目标主机发送icmp请求包 常用来测试当前主机与目标主机网络连接状况 常见选项 -c 设置发包的个数 -s 设置发的包的块大小&#xff0c;最大不超过65507 -W 设置接收回应超时时间 -i …

java printwriter实例_PrintWriter做过滤流+FileWriter案例分析

package com.mstf.ui;import java.io.*;public class TestWriter{public static void main(String args[]){//PrintWriter做过滤流FileWriter//doFilter1();//2、PrintWriter做过滤流OutputStreamWriter//doFilter2();//3、PrintWriter可以作为节点流//doNode();//4、PrintWrit…

treemap比较器_Java TreeMap比较器()方法与示例

treemap比较器TreeMap类的compare()方法 (TreeMap Class comparator() method) comparator() method is available in java.util package. 比较器()方法在java.util包中可用。 comparator() method is used to return the key element in this TreeMap based on the Comparator…

洛谷P1204 [USACO1.2]挤牛奶Milking Cows 前缀和

这题数据比较水 暴搜都能够过去 1 #include <cstdio>2 #include <cmath>3 #include <cstdlib>4 #include <algorithm>5 #include <string>6 #include <iostream>7 #include <iomanip>8 #include <cstring>9 using namespace s…

java script创建对象_JavaScript七种非常经典的创建对象方式

JavaScript创建对象的方式有很多&#xff0c;通过Object构造函数或对象字面量的方式也可以创建单个对象&#xff0c;显然这两种方式会产生大量的重复代码&#xff0c;并不适合量产。接下来介绍七种非常经典的创建对象的方式&#xff0c;他们也各有优缺点。一、工厂模式可以无数…

java 方法 示例_Java扫描仪具有示例的NextNextInt()方法

java 方法 示例扫描器类的hasNextInt()方法 (Scanner Class hasNextInt() method) Syntax: 句法&#xff1a; public boolean hasNextInt();public boolean hasNextInt(int rad);hasNextInt() method is available in java.util package. hasNextInt()方法在java.util包中可用…

axis2开发webservice之编写Axis2模块(Module)

axis2中的模块化开发。能够让开发者自由的加入自己所需的模块。提高开发效率&#xff0c;减少开发的难度。 Axis2能够通过模块&#xff08;Module&#xff09;进行扩展。Axis2模块至少须要有两个类&#xff0c;这两个类分别实现了Module和Handler接口。开发和使用一个Axis2模块…

java 看书浏览器官_JAVA读取文件流,设置浏览器下载或直接预览操作

最近项目需要在浏览器中通过url预览图片。但发现浏览器始终默认下载&#xff0c;而不是预览。研究了一下&#xff0c;发现了问题&#xff1a;// 设置response的header&#xff0c;注意这句&#xff0c;如果开启&#xff0c;默认浏览器会进行下载操作&#xff0c;如果注释掉&…