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

题意:

有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;
}
posted @ 2013-01-21 23:15  kedebug  阅读(338)  评论(0编辑  收藏  举报