题目描述
A little known fact about Bessie and friends is that they love stair climbing races. A better known fact is that cows really don’t like going down stairs. So after the cows finish racing to the top of their favorite skyscraper, they had a problem. Refusing to climb back down using the stairs, the cows are forced to use the elevator in order to get back to the ground floor.
The elevator has a maximum weight capacity of W (1 <= W <= 100,000,000) pounds and cow i weighs C_i (1 <= C_i <= W) pounds. Please help Bessie figure out how to get all the N (1 <= N <= 18) of the cows to the ground floor using the least number of elevator rides. The sum of the weights of the cows on each elevator ride must be no larger than W.
给出n个物品,体积为w[i],现把其分成若干组,要求每组总体积<=W,问最小分组。(n<=18)
输入输出格式
输入格式:
Line 1: N and W separated by a space.
Lines 2..1+N: Line i+1 contains the integer C_i, giving the weight of one of the cows.
输出格式:
- A single integer, R, indicating the minimum number of elevator rides needed.
one of the R trips down the elevator.
输入输出样例
输入样例#1:
4 10
5
6
3
7
输出样例#1:
3
说明
There are four cows weighing 5, 6, 3, and 7 pounds. The elevator has a maximum weight capacity of 10 pounds.
We can put the cow weighing 3 on the same elevator as any other cow but the other three cows are too heavy to be combined. For the solution above, elevator ride 1 involves cow #1 and #3, elevator ride 2 involves cow #2, and elevator ride 3 involves cow #4. Several other solutions are possible for this input.
解题思路
看数据范围,状态dp。设dp[S]为S这个状态的最小需要电梯数,发现这样并不能去转移,所以需要一个辅助数组g[S]表示在这个状态下最优时这个电梯的空间。转移时细节要注意。时间复杂度O(2^n*n)
代码
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int dp[1<<19],g[1<<19];
int w[20],n,V;
int main() {
memset(dp,0x3f,sizeof(dp));
dp[0]=0;
scanf("%d%d",&n,&V);g[0]=V;
for(register int i=1; i<=n; i++) scanf("%d",&w[i]);
for(register int i=0;i<1<<n;i++) g[i]=V;
for(register int S=0; S<1<<n; S++)
for(register int i=1; i<=n; i++){
int ff=0,gg=0;
if(!((1<<i-1)&S)) {
if(g[S]>=w[i]) {
ff=dp[S];
gg=g[S]-w[i];
} else{
gg=V-w[i];
ff=dp[S]+1;
}
if(dp[S|(1<<i-1)]>ff){
g[S|(1<<i-1)]=gg;
dp[S|(1<<i-1)]=ff;
}
else if(dp[S|(1<<i-1)]==ff && g[S|(1<<i-1)]<gg) //次数一样比空间
g[S|(1<<i-1)]=gg;
}
}
if(g[(1<<n)-1]!=V) dp[(1<<n)-1]++; //如果还有几个牛在电梯上
printf("%d",dp[(1<<n)-1]);
return 0;
}