状压dp最小分组

题目描述

A little known fact about Bessie and friends is that they love stair climbing races. A better known fact is that cows really don't like going down stairs. So after the cows finish racing to the top of their favorite skyscraper, they had a problem. Refusing to climb back down using the stairs, the cows are forced to use the elevator in order to get back to the ground floor.

The elevator has a maximum weight capacity of W (1 <= W <= 100,000,000) pounds and cow i weighs C_i (1 <= C_i <= W) pounds. Please help Bessie figure out how to get all the N (1 <= N <= 18) of the cows to the ground floor using the least number of elevator rides. The sum of the weights of the cows on each elevator ride must be no larger than W.

给出n个物品,体积为w[i],现把其分成若干组,要求每组总体积<=W,问最小分组。(n<=18)

输入格式

* Line 1: N and W separated by a space.

* Lines 2..1+N: Line i+1 contains the integer C_i, giving the weight of one of the cows.

输出格式

* A single integer, R, indicating the minimum number of elevator rides needed.

one of the R trips down the elevator.

#include<iostream>
#include<cstring>
using namespace std;
const int maxn=20;
int dp[1<<maxn];
int g[1<<maxn];
int val[maxn];
int main()
{
    int n,w;cin>>n>>w;
    for(int i=0;i<n;i++) cin>>val[i];
    memset(dp,0x3f,sizeof(dp));
    dp[0]=1;
    g[0]=w;
    for(int i=0;i<(1<<n);i++)
    {
        for(int j=0;j<n;j++)
        {
            if((i>>j)&1) continue;
            if(g[i]>=val[j]&&dp[i|(1<<j)]>=dp[i])
            {
                dp[i|(1<<j)]=dp[i];
                g[i|(1<<j)]=max(g[i|(1<<j)],g[i]-val[j]);
            }
            else if(g[i]<val[j]&&dp[i|(1<<j)]>=dp[i]+1)
            {
                dp[i|(1<<j)]=dp[i]+1;
                g[i|(1<<j)]=max(g[i|(1<<j)],w-val[j]);
            }
        }
    }
    cout<<dp[(1<<n)-1]<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值