POJ 2923 Relocation(状态压缩 + 两次DP)

本文介绍了一个经典的家具搬运问题,通过状态压缩和二次背包算法求解最少搬运次数。利用两辆不同容量的搬运车来搬运数量不多于10件的家具。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

有n个家具要搬运,两辆搬运车的容量分别是c1, c2,搬运的过程要求两辆搬运车一起来回。问最少需要多少趟能把家具搬完。

思路:

1. 因为n的范围是 n <= 10, 所以可以把家具压缩成状态 s

2. 判断状态 s 所表达的家具是否能有两辆车一次搬运完成,如果能则把状态 s 在 state[] 数组记录下来为 state[] = s

3. 对 state[] 状态数组再进行一次背包,状态的价值为 1,求最少需要多少趟能完成搬运 :dp[s|state[i]] = min(dp[s|state[i]], dp[s] + 1);

 

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

int w[20];
int n, C1, C2;
int dp[1100], state[1100];
bool pack[1100];

bool judge(int s)
{
    int sum = 0;
    
    memset(pack, false, sizeof(pack));
    pack[0] = true;

    for (int i = 0; i < n; ++i)
        if (s & (1 << i))
        {
            sum += w[i];
            for (int v = C1; v >= w[i]; --v)
                if (pack[v-w[i]])
                    pack[v] = true;
        }
    for (int v = 0; v <= sum; ++v)
        if (pack[v] && sum - v <= C2)
            return true;

    return false;
}

int main()
{
    int cases;
    int cnt = 0;
    scanf("%d", &cases);
    while (cases--)
    {
        scanf("%d %d %d", &n, &C1, &C2);
        for (int i = 0; i < n; ++i)
            scanf("%d", &w[i]);

        int m = 0;
        const int inf = (1 << n) - 1;

        memset(dp, 0x3f, sizeof(dp));
        memset(state, 0, sizeof(state));

        for (int s = 0; s <= inf; ++s)
            if (judge(s))
                state[m++] = s;

        dp[0] = 0;
        for (int i = 0; i < m; ++i)
            for (int s = inf - state[i]; s >= 0; --s)
                if (!(s & state[i]))
                    dp[s|state[i]] = min(dp[s|state[i]], dp[s] + 1);

        printf("Scenario #%d:\n%d\n\n", ++cnt, dp[inf]);
    }
    return 0;
}

转载于:https://www.cnblogs.com/kedebug/archive/2013/01/21/2870572.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值