题目描述;
Emma and Eric are moving to their new house they bought after returning from their honeymoon. Fortunately, they have a few friends helping them relocate. To move the furniture, they only have two compact cars, which complicates everything a bit. Since the furniture does not fit into the cars, Eric wants to put them on top of the cars. However, both cars only support a certain weight on their roof, so they will have to do several trips to transport everything. The schedule for the move is planed like this:
- At their old place, they will put furniture on both cars.
- Then, they will drive to their new place with the two cars and carry the furniture upstairs.
- Finally, everybody will return to their old place and the process continues until everything is moved to the new place.
Note, that the group is always staying together so that they can have more fun and nobody feels lonely. Since the distance between the houses is quite large, Eric wants to make as few trips as possible.
Given the weights wi of each individual piece of furniture and the capacities C1 and C2 of the two cars, how many trips to the new house does the party have to make to move all the furniture? If a car has capacity C, the sum of the weights of all the furniture it loads for one trip can be at most C.
你有两辆卡车和n个物品,每个物品有自己的重量,你需要多少次搬运才能将物品搬完。
输入T,测试组数,然后n,n个物品,C1,C2两辆卡车的载重,下一行n个物品的重量。n≤10;
样例:
input:
2 6 12 13 3 9 13 3 10 11 7 1 100 1 2 33 50 50 67 98
output:
Scenario #1: 2 Scenario #2: 3但看这道题看起来很复杂,物品和卡车的选取情况太多,但其实数据范围给了一个非常重要的提示,n最多只有10,也就是说物品非常少,那么我们就可以用状态压缩的方式将这些复杂的情况的简化。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<string>
#include<stack>
#include<queue>
#include<algorithm>
#include"stdlib.h"
using namespace std;
const int MAXM=1010;
const int INF=999999999;
int n,C1,C2;
int w[2010];
int dp[2010];
int state[2010];
bool vis[2010];
void init()
{
for (int i=0;i<(1<<n);i++)
dp[i]=INF;
}
bool check(int x)
{
int sum=0;
memset(vis,false,sizeof(vis));
vis[0]=true;
for (int i=0;i<n;i++)
{
if ((x>>i)&1)
{
sum+=w[i];
for (int j=C1;j>=w[i];j--)
if (vis[j-w[i]])
vis[j]=true;
}
}
if (sum>C1+C2)
return false;
for (int j=0;j<=C1;j++)
if (vis[j]&&sum-j<=C2)
return true;
return false;
}
int main()
{
int T;
scanf("%d",&T);
int cas=1;
while(T--)
{
scanf("%d%d%d",&n,&C1,&C2);
init();
for (int i=0;i<n;i++)
scanf("%d",&w[i]);
int tot=0;
for (int i=0;i<(1<<n);i++)
if (check(i))
state[tot++]=i;
dp[0]=0;
for (int i=0;i<tot;i++)
{
for (int j=(1<<n)-1;j>=0;j--)
{
if (j&state[i]) continue;//判断物品是否被重复选取
if (dp[j]==INF) continue;
dp[j|state[i]]=min(dp[j|state[i]],dp[j]+1);
}
}
printf("Scenario #%d:\n",cas);
cas++;
printf("%d\n\n",dp[(1<<n)-1]);
}
return 0;
}