POJ Relocation 状态压缩 01背包
来源:互联网 发布:淘宝联盟不能和红包 编辑:程序博客网 时间:2024/05/01 16:35
题意:某夫妻要搬家。他们有两辆车,容量分别为C1,C2。有N个家具,体积为Ci。两人分别驾驶一辆车搬家具,至少要用几次才能把家具办完。
思路:咋看这道题,没有思路。
观察了很久,才发现,在向车装入家具的时候,家具的顺序是没有关系的,对于家具比较重要的其实是把他放到哪辆车和第几次上。
因为顺序的无序性,我们就能想到了集合,以及用数来表示集合,这样最终我们是要把集合从0变成2^N-1.这样,我们就引入了状态压缩。
因为最终求最少的次数,把所有所有家具搬完。就是把两辆车看成一个整体,然后对家具进行搬运。
当我们知道一次中,所有的搬运方案,同时因为每件家具至多被搬运一次,这就转化成了01背包问题。
这样整体算法过程已经清晰。
首先,我们对每辆车求出所有可行的搬运方案。
然后求,两辆车作为一个整体的搬运方案。这个要保证两个车搬运的东西是不同的。
然后,我们利用01背包,用搬运的东西作为状态进行转移。同样,这里也要保证已经搬运的和即将搬运的是不同的东西。
代码如下:
#include <cstdio>#include <algorithm>#include <cstring>#include <iostream>#include <bitset>using namespace std;const int MAX = 11;int T,N,C1,C2;int v[1<<MAX],v1[1<<MAX],v2[1<<MAX],sz,sz1,sz2;int w[MAX],used[1<<MAX],dp[1<<MAX];bool judge1(int s){ int sum = 0; for(int i = 0; i < N; ++i) if((s>>i) & 1) sum += w[i]; return sum <= C1;}bool judge2(int s){ int sum = 0; for(int i = 0; i < N; ++i) if((s>>i) & 1) sum += w[i]; return sum <= C2;}int main(void){ //freopen("input.txt","r",stdin); scanf("%d",&T); for(int cas = 1; cas <= T; ++cas){ scanf("%d%d%d",&N,&C1,&C2); for(int i = 0; i < N; ++i) scanf("%d",&w[i]); sz = sz1 = sz2 = 0; int all = (1<<N) - 1; for(int i = 0; i <= all; ++i){ if(judge1(i)) v1[sz1++] = i; if(judge2(i)) v2[sz2++] = i; } memset(used,0,sizeof(used)); for(int i = 0; i < sz1; ++i) for(int j = 0; j < sz2; ++j) if((v1[i] & v2[j]) == 0) used[v1[i] | v2[j]] = 1; for(int i = 0; i <= all; ++i) if(used[i]) v[sz++] = i; memset(dp,0x3f,sizeof(dp)); dp[0] = 0; for(int i = 0; i < sz; ++i){ for(int s = all; s >= 0; --s){ int u = s ^ v[i]; if(u != (s | v[i])) continue; dp[u] = min(dp[u],dp[s]+1); } } printf("Scenario #%d:\n%d\n\n",cas,dp[all]); } return 0;}
0 0
- poj 2923 Relocation(状态压缩+01背包)
- poj 2923 Relocation 状态压缩01背包
- poj 2923 Relocation 状态压缩+01背包
- POJ 2923 - Relocation(状态压缩+01背包)
- POJ Relocation 状态压缩 01背包
- POJ 2923 Relocation(状态压缩+01背包)
- POJ 2923 Relocation(状态压缩+ 01背包)
- poj 2923 Relocation (枚举+背包 | 状态压缩+01背包)
- poj 2923 Relocation(状态压缩+01背包)
- poj 2923 Relocation(DP+状态压缩+01背包)
- POJ 2923 Relocation(状态压缩DP+DP:01背包)
- poj 2923 Relocation(状态压缩+01背包)
- poj 2923 Relocation(状态压缩加上01背包)
- POJ 2923 Relocation(状态压缩+01背包)
- poj 2923 Relocation (01背包+状态压缩)
- POJ 2923 Relocation (状态压缩+背包)
- POJ 2923 Relocation(状态压缩+背包思想)
- poj2923 Relocation (01背包+状态压缩)
- JAVAWEB项目如何实现验证码
- 正数相减少
- gephi使用说明
- 遗传算法入门例子和总结
- Java异常的介绍及处理
- POJ Relocation 状态压缩 01背包
- pajek使用说明
- ubuntu 更新内核切换内核启动
- Mutex v/s Semaphore v/s Spinlock
- 畅通工程
- linux下安装配置svn独立服务器
- OpenFire源码学习之十:连接管理(上)
- HDU 1051 Wooden Sticks
- 微信开放11类接口:开发者可基于微信打造真正Web应用