P3052
[USACO12MAR]Cows in a Skyscraper G
题目描述
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
样例输入 #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.
本来正解是状压 但是这种题一看首先肯定还是用DFS
但这题的DFS搜索剪枝等很有技巧
首先有个很关键的点:若先对数组排序会严重超时!最好的当然是用random_shuffle随机化打乱数列
然后 并不需要高深的迭代加深或者模拟退火
只用一般的爆搜即可
但要注意:最优性剪枝(不必多说)
每次DFS中枚举的是目前这个物品装第几个箱子 而这个枚举上界可以剪枝!
考虑最坏的情况就是一个物品一个箱子 所以减去放在同一个箱子(可能有很多个不同的箱子)中的物品
那么剩下来的按一个物品一个箱子分即可确定上界!
还有几个细节:
1.再开个数组存每个箱子剩余的体积 若剩余体积=初始体积 就新开一个箱子 否则就是多个物品放一个箱子的case
2.回溯是要先将该箱子的剩余体积先补上(先回溯)再判断是新开的箱子还是已经有物品的箱子的情况 否则RE!!!
总之 这是一道很好的搜索题!
点击查看代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,w,a[19],ans=LONG_MAX,res[19],tot;
void dfs(int step,int cnt)
{
if(step==n+1)
{
ans=min(ans,cnt);
return ;
}
if(cnt>=ans)return ;
for(int i=1;i<=step-tot;i++)
{
if(res[i]<a[step])continue;
if(res[i]==w)cnt++;//用了一个新的箱子
if(res[i]!=w) tot++;
res[i]-=a[step];
dfs(step+1,cnt);
res[i]+=a[step];
if(res[i]==w)cnt--;
if(res[i]!=w) tot--;
}
return ;
}
signed main()
{
ios::sync_with_stdio(false);
cin>>n>>w;
for(int i=1;i<=n;i++)cin>>a[i],res[i]=w;
// sort(a+1,a+n+1);
dfs(1,0);
cout<<ans<<"\n";
return 0;
}

浙公网安备 33010602011771号