奥利奥 · 2016-03-28 18:16:00 · 老王装货
关于老王装货的学习资料的汇总
160902113 · 2015-09-25 20:18:06
不解释,背包问题。。。。。。
huangcoder · 2015-09-26 00:28:41
$a=array(509,838,924,650,604,793,564,651,697,649,747,787,701,605,644);
$len=count($a);
for($i=1;$i<$len;$i++)
{
for($j=$len-1;$j>=$i;$j--)
if($a[$j]>$a[$j-1])
{//如果是从大到小的话,只要在这里的判断改成if($b[$j]>$b[$j-1])就可以了
$x=$a[$j];
$a[$j]=$a[$j-1];
$a[$j-1]=$x;
}
}
$num=0;
foreach($a as $val){
if($num<5000){
$num+=$val;
echo $val;
echo "<br>";
echo $num;
echo "<br>";
}else{
exit;
}
}冒泡排序一下 正序 和 反序 分别累加 得到要有六个或七个数值才能接近或不超过5000
for($i=0;$i<10000000;$i++){
$b=array_rand($a,7);
//var_dump($b);
$num=0;
$lianjie=" ";
foreach($b as $val){
$num+=$a[$val];
$val=$val+1;
$lianjie.=$val."-";
}
if(4988<$num&&$num<5000){
echo $num.":".$lianjie;
echo "<br>";
}
}在数值中 做100万随机取出六个或七个值累加 取出来大于4988小于5000
跑了好几次 也就能跑出 4989: 2-6-7-9-10-11-13-
求问 4991 怎么得来的
mdep · 2015-09-27 05:21:11
因为输入规模比较小,可以用SMT求解器爆破。
用SMT的语言来描述一下这个问题:
有15个变量,每个变量要么是0(表示不拿),要么是对应的重量
这15个变量的和不超出5000
求和的最大值(还有每个变量对应的值)
好像就是把问题复述一遍而已?
约束条件:
constrains vars = (bAnd $ zipWith (\g v -> v .== fromIntegral g ||| v .== 0) goods vars) &&& (sum vars .< 5000)(goods是商品数组)
求最大值:
maximize Quantified sum (length goods) constrains然后结果就出来了。
参考:
zzliux · 2015-09-27 19:12:48
我来写个简单的题解吧
这个只是个01背包的题目,模版算不上
质量等于价值
for i=0 to 15
for j=5000 to v[i]
if dp[j]<dp[j-v[i]+v[i] then
dp[j]=dp[j-v[i]]+v[i]
for k=0 to 15
mark[dp[j]][k]=mark[j-v[i]][k]
end for
mark[dp[j]][i+1]=1
end if
end for
end for伪代码.
dp[k]表式0~k的容量能最多放进物品的价值
markm表示价值m的组合中第n个是否被选中
输出就是
for i=1 to 16
if mark[dp[5000]][i] == 1 then
print i
end if
end for
you…(邮箱样式的昵称,已隐去) · 2015-11-05 17:58:12
参考百度百科 献丑了 百度百科-01背包问题
int good[]={509,838,924,650,604,793,564,651,697,649,747,787,701,605,644};
int max=5000;
int result;
void main() {
make(good.length-1, max);
}
private int make(int i, int lastRoom) {
if (i == 0) {
return 0;
}
int put=0;
if (lastRoom > good[i]) {
put = make(i - 1, lastRoom - good[i]) + good[i];
}
int notPut = make(i-1, lastRoom);
if (lastRoom > good[i] && put <= max) {
Timber.d("put "+i+" "+put);
result=put > result?put:result;
}
if (notPut <= max) {
Timber.d("notPut "+i+" "+notPut);
result=notPut > result?notPut:result;
}
if (lastRoom > good[i] && put > notPut) {
return put;
} else {
return notPut;
}
}
BluesCode · 2015-11-08 16:12:33
参考自 动态规划 之 0-1背包问题
#include <iostream>
#include <string>
using namespace std;
/*
* arg
w: 物品重量数组,第一个元素不用,从第二个元素开始算起
n: 物品数量
c: 背包总容量
*/
int MaxBag(int* w, int n, int c)
{
//定义:前n个物品放在总容量为c的背包中的最大值
int temp_v[n+1][c+1];
//初始化为0
for(int i=0; i<n+1; i++)
{
for(int j=0; j<c+1; j++)
{
temp_v[i][j] = 0;
}
}
//计算前i个物品能获得的最大值
for(int i=1; i<n+1; ++i)
{
//第i个物品放在容量为j的背包中能获得的最大值
for(int j=1; j<c+1; ++j)
{
//如果第i个物品的重量小于背包总容量
if(w[i] <= j)
{
//则判断第i个物品价值加上前i-1个物品的价值是否大于前i-1个物品的最大价值
//这里要注意都是根据当前背包的容量计算的
if(w[i]+temp_v[i-1][j-w[i]] > temp_v[i-1][j])
{
temp_v[i][j] = w[i]+temp_v[i-1][j-w[i]];
}else
{
temp_v[i][j] = temp_v[i-1][j];
}
}else
{
temp_v[i][j] = temp_v[i-1][j];
}
}
}
//输出哪个物品被选中,根据temp_v数组的值来判断
int temp_c = c;
//从最后一个元素开始算起
for(int i=n; i>=1; --i)
{
//如果当前背包容量大于物品的重量
if(temp_c >= w[i])
{
//如果前i个物品减去前n-1个物品的最大价值等于第i个物品的重量,则表示当前物品放入背包中
//注意依据背包容量
if(temp_v[i][temp_c]-temp_v[i-1][temp_c-w[i]] == w[i])
{
cout<<i<<" ";
temp_c = temp_c - w[i];
}
}
}
cout<<endl;
return temp_v[n][c];
}
int main()
{
//物品重量数组,方便理解,第一个元素不用,设为0
int w[] = {0,509,838,924,650,604,793,564,651,697,649,747,787,701,605,644};
int max = MaxBag(w,15,5000);
cout<<"Max value is "<<max;
return 0;
}
zhaohao · 2015-11-25 23:42:18
经典01背包问题
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 5001;
int dp[20][N];
int a[20];
void prin(int i, int j)
{
if(!i) return;
if(dp[i][j] == dp[i-1][ j-a[i] ] + a[i])
{
prin(i-1, j-a[i]);
printf("%d-", i);
}
else
prin(i-1, j);
}
int main(void)
{
int i, j;
int n = 15;
for(i = 0; i < n; i++)
{
int x, y;
scanf("%d%d", &x, &y);
a[x] = y;
}
for(i = 1; i <= n; i++)
{
for(j = 5000; j >= a[i]; j--)
{
dp[i][j] = dp[i-1][j];
dp[i][j] = max(dp[i-1][j], dp[i-1][ j-a[i] ]+a[i]);
}
for(j = 0; j < a[i]; j++) dp[i][j] = dp[i-1][j];
}
printf("%d\n", dp[15][5000]);
prin(15, 5000);
printf("\n");
return 0;
}
.info · 2015-12-03 12:54:12
1.排序,然后算出最多,最少,两组求和最接近5000的数组长度
2.选择排列,并对每一个组合求和,得到最接近5000的是4991,输出组合。。。复杂度好大的说。。。
看了别人说是背包问题。百度了一下。。没看懂。。。来个简单易懂的链接。谢谢各位大神!
windroid · 2015-12-04 22:50:57
python递归版
conduct = [ 509, 838, 924, 650, 604, 793 564, 651, 697, 649, 747, 787, 701, 605, 644]
def solv(i, j):
"求最大值 i文件编号,j权重"
if(i < 0):
return 0
if(j>conduct[i]):
rt = max(solv(i-1, j), solv(i-1, j-conduct[i])+conduct[i])
return rt
else:
return solv(i-1, j)
ans = solv(14, 5000)
print(ans)
def search(i, j):
"求解路径"
summer = 0
while(i>=0 and j>=0):
if(solv(i, j) == solv(i-1, j-conduct[i])+conduct[i]):
summer += conduct[i]
print("index:"+str(i+1)+" weight:"+str(conduct[i]))
j -= conduct[i]
i -= 1
return summer
print(search(14, 5000))
天昊 · 2015-12-12 16:22:09
重复发了,再次编辑删掉。
开心 · 2015-12-18 16:25:04
可利用深度优先算法进行遍历,在条件不满足的时候进行回溯,并保存至今最大的装货重量及路径。可利用递归或堆栈实现,一下代码为C语言的堆栈实现。**
phdbrianlee · 2015-12-19 13:35:35
python的迭代器
import itertools
def combinations(n):
dict = {'1':'509','2':'838','3':'924','4':'650','5':'604','6':'793','7':'564','8':'651','9':'697','10':'649','11':'747','12':'787','13':'701','14':'605','15':'644'}
max_n = 0
comStr = ''
for combination in itertools.combinations(dict,n):
sum = 0
for key in combination:
sum = sum + int(dict[key])
comStr = comStr + '-' + str(key)
if (sum > max_n):
max_n = sum
comStr = comStr
break
newDict = {comStr:max_n}
print newDict
return newDict #max_n
def laowang():
max = 0
key = ''
for i in range(1,15):
dictResult = combinations(i)
temp_key = dictResult.keys()[0]
#print temp_key
temp = dictResult.values()[0]
#print 'temp: ' + str(temp)
if ( temp < 5000) and (temp >max ):
max = temp
key = temp_key
print max
print key
九指神丐 · 2016-01-02 00:52:16
import itertools
dict = {'1':509,'2':838,'3':924,'4':650,'5':604,'6':793,'7':564,'8':651,'9':697,'10':649,'11':747,'12':787,'13':701,'14':605,'15':644}
def permutation(adict):
w_min = 4000
d_tmp = None
for d in list(itertools.combinations(adict.items(),7)):
sum_w = sum([y for x,y in d])
if(sum_w> w_min and sum_w < 5000):
w_min = sum_w
d_tmp = d
mydict = sorted(list(d_tmp),key=lambda tuple_a:int(tuple_a[0]))
print mydict
print '-'.join([x for x,y in mydict])
permutation(dict)
fujiaozhu · 2016-01-10 20:11:16
// 数据15,状压DP
int main() {
int sum = 0, res = 0;
int val[15] = {509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644};
for(int i = 0; i <= 1 << 15; i ++) {
int tmp = 0;
for(int j = 0; j < 15; j ++) {
if(i >> (14 - j) & 1)
tmp += val[j];
}
if(sum < tmp && tmp <= 5000) {
sum = tmp;
res = i;
}
}
cout << sum << endl;
for(int i = 0; i < 15; i ++)
if(res >> (14 - i) & 1)
cout << i + 1 << endl;
return 0;
}
wxfwxf328 · 2016-01-12 18:53:47
#include <stdio.h>
int main() {
int i,j, max = -1, key = -1, a[] = {509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644};
for (i = 0; i < 1<<15; i++) {
int sum = 0;
for (j = 0; 1<< j <=i; j++) {
if (i&1<<j) {
sum += a[j];
}
}
if (sum > max && sum <= 5000) {
max = sum;
key = i;
}
}
printf("%d\n", max);
for (j = 0; 1<< j <=key; j++) {
if (key& 1<<j) {
printf("%d-", j + 1);
}
}
return 0;
}
星级专家 · 2016-01-14 13:57:04
网上看了下教程,看了两个小时没看懂。实在是不会算,但好歹咱可以猜一下。于是猜了半个小时终于猜出来了。
sandy · 2016-01-14 15:05:05
public class Cal01 {
private static int good[]={0,509,838,924,650,604,793,564,651,697,649,747,787,701,605,644};
private static int max=5000;
/**动态规划 - 两种方案,选择装的多的
@param i 第几件货物
@param lastRoom 剩余空间
@return 最多能装下多少货物
*/
int make(int i, int lastRoom){
if(i==0){
return lastRoom>good[i]?good[i]:0;
}
int put=0;
if(lastRoom>good[i]){
put=make(i-1,lastRoom-good[i])+good[i];
}
int notPut=make(i-1,lastRoom);
return put>notPut?put:notPut;}
public static void printGood(int max){
int temp=max;
for(int i=good.length-1;i>=1;i--){
if(temp>=good[i]){
if(make(i,temp)-make(i-1,temp-good[i])==good[i]){
System.out.println("put"+i);
temp=temp-good[i];
}
}
}
}
static void main(String[] args) {
// TODO Auto-generated method stub
int result=make(good.length-1,max);
System.out.println(result);
printGood(max);}
}
lucifer · 2016-01-21 10:58:09
可以通过整数规划来解。
h · 2016-01-31 14:50:37
不懂算法的小白一名,用R生成随机序列穷解。
a <- c(509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644)
l <- list()
## 1e4很快,但是不是每次都能得出最优解,1e5较慢,但是稳当~
for (i in 1:1e4) {
m <- sample.int(2,15,T)-1
r <- 5000-sum(a*m)
i <- paste0("i",i)
if (r>=0) l[[i]] <- list(reminder = r, method = m)
}
print(paste0(which(l[[which.min(sapply(l, function(x){x$reminder}))]]$method>0),collapse = "+"))
update
用排列组合,遍历一遍,不再随机了=。=
bag <- function (books, limit) {
numb <- length(goods)
cumSumAscent <- sapply(1:numb,function(i){sum(sort(goods)[1:i])})
nuMax <- which.max(cumSumAscent[cumSumAscent < limit])
cumSumDescent <- sapply(1:numb,function(i){sum(sort(goods,T)[1:i])})
nuMin <- which.max(cumSumDescent[cumSumDescent < limit])
weight <- limit
way <- 0
j <- 0
for (i in nuMin:nuMax) {
for (j in seq(factorial(numb) / factorial(i) / factorial(numb - i))) {
thisWay <- gtools::combinations(numb, i)[j, ]
thisRoom <- limit - sum(goods[thisWay])
if (thisRoom > 0 && thisRoom < weight) {
weight <- thisRoom
way <- thisWay
}
}
}
return(list(weight = weight, way = way))
}
goods <- c(509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644)
limit <- 5e3
bag(goods,limit)
kodoyang · 2016-02-02 11:05:41
文少 · 2016-02-11 21:39:30
var products = new[] { 509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644 };
var max = (int)(Math.Pow(2, products.Length) - 1);
Observable.Range(1, max)
.Select(x =>
{
return Enumerable.Range(0, products.Length)
.Select(o => new { num = o, pow = (int)Math.Pow(2, o) })
.Where(o => (x & o.pow) == o.pow)
.Select(o => o.num);
})
.Select(x => new { sum = x.Sum(o => products[o]), indexs = x })
.Where(x => x.sum <= 5000)
.MaxBy(x => x.sum)
.Subscribe(x =>
{
Console.WriteLine(x.First().sum);
Console.WriteLine(string.Join("-", x.First().indexs));
});
何以随风 · 2016-02-19 14:42:07
研究了一天DP懵懵懂懂,值倒是很早算出了,就是不知道取哪个的问题,一直没想通。
liuyichao · 2016-02-25 16:59:29
既然是DP,好吧,既然没有python版本的,好吧。
补上一个
__author__ = 'liuyichao'
arr = [509,838,924,650,604,793,564,651,697,649,747,787,701,605,644]
dp = []
for i in range(0,5010):
dp.append(0)
x = range(0,5001)
x.reverse()
for item in arr:
for i in x:
if i >= item:
dp[i] = max([dp[i],dp[i-item]+item])
print dp[5000]
ans = []
st = 5000
for item in arr:
if dp[st-item] == dp[st] - item:
ans.append(item)
st -= item
print ans
print '-'.join(map(lambda item:str(arr.index(item)+1),ans))
shawncoder · 2016-04-20 14:34:50
查资料看了2个小时,还是没看到,算法这方面很欠缺,最近在学C++,准备学习学习算法!
kirai · 2016-04-23 16:54:29
动态规划 01背包问题+记录路径。O(n)解法水果
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <complex>
#include <fstream>
#include <cassert>
#include <cstdio>
#include <bitset>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
#include <cmath>
using namespace std;
const int maxn = 55050;
int w[maxn];
int n, W;
int dp[maxn];
int vis[25][maxn];
int main() {
// freopen("in", "r", stdin);
scanf("%d %d", &n, &W);
memset(dp, 0, sizeof(dp));
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n; i++) {
scanf("%d", &w[i]);
}
for(int i = n; i >= 1; i--) {
for(int j = W; j >= w[i]; j--) {
if(dp[j] < dp[j-w[i]]+w[i]) {
dp[j] = dp[j-w[i]] + w[i];
vis[i][j] = 1;
}
}
}
for(int i = 1, j = dp[W]; i <= n, j > 0; i++) {
if(vis[i][j]) {
printf("%d \n", w[i]);
j -= w[i];
}
}
return 0;
}
nemoomen · 2016-04-24 13:36:56
我不是针对谁,我是说写完代码不运行的都是垃圾,本来想看看有没有写对的结果一运行,全是错的,最基础的错。有的大神还是重新学学语法基础再来发代码好么,别浪费别人时间来装**
warlock · 2016-04-27 11:19:45
用了遍历的方式,代码比较好理解,给大家参考
public class Answer25 {
static int good[] = {509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644};
static int LIMIT = 5000;
public static void main(String[] args) {
int maxWeight = 0;
String maxMethod = "";
for (int i = 0; i < 1 << good.length; i++) {
String method = Integer.toBinaryString(i);
while (method.length() < good.length) {
method = "0" + method;
}
int sum = 0;
for (int j = 0; j < method.length(); j++) {
if (method.charAt(j) == '1') {
sum += good[j];
}
if (sum > LIMIT) {
break;
}
}
if (sum <= LIMIT && sum > maxWeight) {
maxWeight = sum;
maxMethod = method;
}
}
String result = "";
int resultWeight = 0;
for (int j = 0; j < maxMethod.length(); j++) {
if (maxMethod.charAt(j) == '1') {
result += (j + 1) + "-";
resultWeight += good[j];
}
}
if (result.length() > 0) {
result = result.substring(0, result.length() - 1);
}
System.out.println(result);
System.out.println(resultWeight);
}
}
HJWAJ · 2016-05-06 04:34:57
我的4991为啥是0分
Roclee · 2016-05-11 15:28:31
背包问题,感觉懂但是上手一写磕磕绊绊的。
#背包问题
items=[509,838,924,650,604,793,564,651,697,649,747,787,701,605,644]
pick=[0 for n in range(15)]
maxsum=5000
def maxweight(i,w):
if i<0:
return 0
elif items[i]<w :
if(((maxweight((i-1),w-items[i])+items[i])>(maxweight(i-1,w)))):
pick[i]=1
return maxweight((i-1),w-items[i])+items[i]
else:
pick[i]=0
return maxweight(i-1,w)
else:
pick[i]=0
return maxweight(i-1,w)
print maxweight(14,maxsum)
s=""
for i in range(0,len(items)):
if pick[i]==1:
s=s+"-"+str(i+1)
print s[1:len(s)]
chensiyi · 2016-06-26 10:48:28
C语言 老司机教你
//author: chensiyi
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 5000
void main() {
int goods[] =
{ 0,509,838,924,650,604,793,564,651,697,649,747,787,701,605,644 };
#define ngoods (sizeof(goods)/sizeof(int)-1)
short bests[max + 1] = { 0 };
short possible[max] = { 0 };
int nOldPossible, npossible = 0;
int i, j, sum;
char buf[ngoods*3] = { 0 };
char *sbuf=buf;
//列出可能及记录路径
//列出方法的说明: 对于集合{509,838},其子集有2^2=4个,这是2个元素的集合的所有可能。
// 对于三个元素的集合,其子集数量等于两倍的两个元素的集合。
// 假如集合A比B多一个元素,则A的可能为所有B的可能增加那个多出来的元素。
// 以表达式的方法来写就是: S(n+1) = S(n) + { C | C={sub(i),e},sub(i)∈S(n),e=A-B }
// 其中,S(x)表示 '含有x个元素的集合的所有子集' 所构成的集合,sub(i)是S(n)中的元素。
//这里的代码不以集合为记录形式,而是以载重为记录形式。所以可能出现一个载重有多个结果。这里只记录第一个出现的结果。
for (i = ngoods; i > 0; --i) {
//相当于记录上面说明中的S(n)的状态。
nOldPossible = npossible;
for (j = nOldPossible; j>=0 ; --j) {
//相当于上面的 C={sub(i),e}
sum = possible[j] + goods[i];
//if保证结果在所需的范围内 并且不记录多径。执行结果为为S(n+1)集合中添加了C元素
if (sum <= max && bests[sum] == 0)
{
//这里记录路径——如果能达到sum大小的载货量,则装了i元素
bests[sum] = i;
possible[++npossible] = sum;
}
}
}
//找到最大载量 由于bests数组初值为0,所以只有记录了路径的位置才不是0。从最大载重开始找到的第一个位置极为最大载量。
for (i = max; bests[i] == 0; --i);
//溯源并输出结果
for (; i > 0; sbuf += sprintf(sbuf, "%d-", bests[i]), i -= goods[bests[i]]);
sbuf[-1] = 0;
puts(buf);
system("pause");
//return 0;
}
czcz · 2016-06-26 12:23:25
var ar = [509,838,924,650,604,793,564,651,697,649,747,787,701,605,644];
orig = 0;
var i = 0;
var num = 0;
for(i=0;i<(1<<15);i++){
var tmp = 0;
var j;
for(j=14;j>=0;j--){
if(((i>>j)&1) == 1){
tmp += ar[15-j];
}
if(tmp > 5000){
break;
}
}
if(tmp > orig && tmp <= 5000){
orig = tmp;
num = i;
}}
console.log(orig);
for(i=14;i>=0;i--){
if(((num>>i)&1) == 1){
console.log(15 - i + 1);
}}