function aaa(){ window.close(); } function ck() { console.profile(); console.profileEnd(); if(console.clear) { console.clear() }; if (typeof console.profiles =="object"){ return console.profiles.length > 0; } } function hehe(){ if( (window.console && (console.firebug || console.table && /firebug/i.test(console.table()) )) || (typeof opera == 'object' && typeof opera.postError == 'function' && console.profile.length > 0)){ aaa(); } if(typeof console.profiles =="object"&&console.profiles.length > 0){ aaa(); } } hehe(); window.onresize = function(){ if((window.outerHeight-window.innerHeight)>200) aaa(); }

P3052 [USACO12MAR]【摩天大楼里的奶牛(Cows in a Skyscraper)】

描述

  N头牛在楼顶,需要坐电梯下来,电梯最大承载量为W,牛 i 的重量为C_i 。

题目

  怎样安排,才能电梯上下的次数最少,而使所有的牛下来。

 

输入输出格式

 

输入

  第一行给出奶牛头数N,及电梯的容量W.接下来N行给出每个奶牛的重量
  1 <= N <= 18   1 <= W <= 100,000,000 ,1<=Ci<=W

输出

  电梯上下的次数R 

 

输入输出样例

 

输入样例1

 

4 10 
5 
6 
3 
7 

 

输出样例1

 

3 
//第一次运1, 3这两头牛 
//第二次运2这一头牛 
//第三次运4这一头牛 

 

解题思路

  这道题我仍然用的DFS的记忆化搜索,a数组是每个电梯的剩余载重,b数组是每头牛的重量,我以奶牛为深度,sum记已开电梯数量,每次搜索时,找已用的电梯,如果能塞就塞进去,最后再重新开一个电梯塞进去,并随时比较剪枝,输出最优解。

题解

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,w,ans=9999;
 4 int a[20];
 5 int b[20];
 6 void dfs(int dep,int sum)
 7 {
 8     if(sum>=ans)
 9     {
10         return;
11     }
12     if(dep==n+1)
13     {
14         ans=sum;
15         return;
16     }
17     for(int i=1;i<=sum;i++)
18     {
19         if(a[i]>=b[dep])
20         {
21             a[i]-=b[dep];
22             dfs(dep+1,sum);
23             a[i]+=b[dep];
24         }
25     }
26         a[sum+1]-=b[dep];
27         dfs(dep+1,sum+1);
28         a[sum+1]+=b[dep];
29 }
30 int main()
31 {
32     cin>>n>>w;
33     for(int i=1;i<=n;i++)
34     {
35         a[i]=w;
36     }
37     for(int i=1;i<=n;i++)
38     {
39         
40         cin>>b[i];
41     }
42     dfs(1,1);
43     cout<<ans;
44 }

 

posted @ 2019-07-09 10:10  华恋~韵  阅读(337)  评论(0编辑  收藏  举报