poj 2923 dp状态压缩+背包(两辆货车来运货)
2014-11-27 20:37
447 查看
题意:有n(1<=n<=10)个货物要从A地运往B地,每个货物的重量为wi。现在有两个货车,载重分别为a和b(输入保证max(a,b)>=任何wi)。已知两辆货车同时运货同时回来,问最少多少趟能把n个货物运送完毕。
思路:首先对n个货物测试哪些组合能够一趟运送完毕,通过状态压缩来做。结果存入s数组。之后进行背包,一个状态state其为1位表示选取对应货物。dp[state]表示运送state表示的货物组合所需要的最少运送趟数。细节见代码
思路:首先对n个货物测试哪些组合能够一趟运送完毕,通过状态压缩来做。结果存入s数组。之后进行背包,一个状态state其为1位表示选取对应货物。dp[state]表示运送state表示的货物组合所需要的最少运送趟数。细节见代码
#include <stdio.h> #include <string.h> #define min(a,b) ((a)<(b)?(a):(b)) #define INF 0x3fffffff #define N 1100 int dp ,s ,w ; int T,n,a,b,m,c=1; int test(int x){ int i,j,used[1100],sum=0; memset(used,0,sizeof(used)); used[0] = 1; for(i = 0;i<n;i++) if(x & (1<<i)){ sum += w[i];//sum是这组货物的总重量 for(j = a-w[i];j>=0;j--) if(used[j]) used[j+w[i]] = 1; } for(i = a;i>=0;i--)//used[i]为1表示i重量的货物可以被a货车运走,看看剩下的能否运走 if(used[i]){ if(sum-i<=b) return 1; return 0; } } int main(){ freopen("a.txt","r",stdin); scanf("%d",&T); while(T--){ int i,j,top = 0; scanf("%d %d %d",&n,&a,&b); m = (1<<n)-1;//总共的状态数量 for(i = 1;i<=m;i++) dp[i] = INF; dp[0] = 0; for(i = 0;i<n;i++) scanf("%d",&w[i]); for(i = 1;i<=m;i++)//测试哪些货物组合是一趟能够运送完毕的 if(test(i)) s[top++] = i; for(i = 0;i<top;i++) for(j = m-s[i];j>=0;j--) if(!(s[i]&j))//表示货物没有重合 dp[s[i]|j] = min(dp[s[i]|j],dp[j]+1); printf("Scenario #%d:\n%d\n\n",c++,dp[m]); } return 0; }
相关文章推荐
- POJ 2923 Relocation(状态压缩DP+DP:01背包)
- POJ 2923 Relocation(01背包变形, 状态压缩DP)
- POJ 2923 Relocation(状态压缩 + 两次DP)
- poj 2923(状态压缩dp)
- POJ 2923 Relocation 状态DP+01背包
- POJ 2923 Relocation 状态压缩DP + 0-1背包
- POJ 2923 dp 状态压缩
- 状态压缩DP——POJ 2923
- 解题报告:POJ_2923 Relocation 状态压缩+01背包
- poj 2923 状态压缩 + 01背包
- poj 2923(状态压缩+背包)
- POJ 2923 Relocation / 状态压缩DP
- POJ 2923 Relocation (状态压缩+背包)
- POJ 2923 Relocation(状态压缩+背包思想)
- poj 2923 状态压缩dp
- POJ - 2923 (01背包,状态压缩)
- POJ 2923 Relocation (状态压缩 0-1背包)
- POJ 2923 Relocation 状态压缩DP + 0-1背包
- POJ 2923 Relocation(状态压缩DP)
- poj 2923 Relocation(状态压缩dp+背包)