1005. Stone Pile 背包问题 动态规划


You have a number of stones with known weights w1, …, wn. Write a program that will rearrange the stones into two piles such that weight difference between the piles is minimal.

Input

Input contains the number of stones n (1 ≤ n ≤ 20) and weights of the stones w1, …, wn (integers, 1 ≤ wi ≤ 100000) delimited by white spaces.

Output

Your program should output a number representing the minimal possible weight difference between stone piles.

Sample

input output
5
5 8 13 27 14
3


这是一个背包问题,发现背包问题自己已经忘记的差不多了,所以决定重新弄清楚。

有N件物品和一个容量为V的背包。第i件物品的重量是w[i],价值是v[i]。
求解将哪些物品装入背包可使这些物品的重量总和不超过背包容量,且价值总和最大。
基础的是01背包问题,特点是每种物品仅有一件,可以选择放或不放。
f[i][v]表示前i件物品恰放入一个容量为v的背包可以获得的最大值。
f[i][v] = max{f[i-1][v],f[i-1][v-w[i]]+v[i]}
压缩为f[v] = max{f[v],f[v-w[i]]+v[i]}
将问题分解为“前i件物品放入容量为v的背包中”这个子问题,如果只考虑第i件物品放入问题,那么就
转化为一个只牵扯前i-1件物品的问题。如果不放第i件物品,那么文件转化为“前i-1件物品放入容量为
v的背包中”,价值为f[i-1][v];如果放第i件物品,问题就转化为“前i-1件物品放入剩下的容量为
v-w[i]的背包中”,此时能获得的最大价值就是f [i-1][v-w[i]]再加上通过放入第i件物品获得的价值v[i].


#include<iostream>
using namespace std;
#define  V 1500
unsigned int f[10][V];//全局变量,自动初始化为0
unsigned int weight[10];
unsigned int value[10];
#define  max(x,y)   (x)>(y)?(x):(y)
int main()
{
    
    int N,M;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值