动态规划(状态压缩):BZOJ 2621 [Usaco2012 Mar]Cows in a Skyscraper

 

2621: [Usaco2012 Mar]Cows in a Skyscraper

Time Limit: 20 Sec  Memory Limit: 128 MB
Submit: 303  Solved: 150
[Submit][Status][Discuss]

Description

[Mark Gordon, Neal Wu, Fatih Gelgi, 2012] 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. 

Input

 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.

Output

* Line 1: A single integer, R, indicating the minimum number of elevator rides needed. * Lines 2..1+R: Each line describes the set of cows taking one of the R trips down the elevator. Each line starts with an integer giving the number of cows in the set, followed by the indices of the individual cows in the set.

Sample Input

4 10
5
6
3
7

Sample Output

3
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 const int INF=1000000000;
 6 const int maxn=1<<20;
 7 int n,W,v[20];
 8 struct Node{
 9     int x,y;
10     Node(int x_=INF,int y_=INF){
11         x=x_;y=y_;
12     }
13     Node operator +(Node b){
14         if(y+b.y>W)
15         return Node(x+b.x+1,b.y);
16         return Node(x+b.x,y+b.y);
17     }
18     bool operator <(const Node &b)const{
19         return x!=b.x?x<b.x:y<b.y;
20     }
21 };
22 Node f[maxn];
23 int cnt,st[maxn];
24 int st2[maxn],tmp;
25 int vis[maxn],tim;
26 int main(){
27     scanf("%d%d",&n,&W);
28     for(int i=1;i<=n;i++)
29         scanf("%d",&v[i]);
30     st[++cnt]=0;f[0].x=f[0].y=0;
31     for(int Ti=1;Ti<=n;Ti++){
32         tim++;
33         for(int j=1;j<=cnt;j++){    
34             for(int i=1;i<=n;i++){
35                 if(st[j]&(1<<(i-1)))
36                     continue;
37                 f[st[j]|(1<<(i-1))]=min(f[st[j]|(1<<(i-1))],f[st[j]]+Node(0,v[i]));
38                 if(vis[st[j]|(1<<(i-1))]!=tim){
39                     st2[++tmp]=st[j]^(1<<(i-1));
40                     vis[st[j]|(1<<(i-1))]=tim;
41                 }
42             }    
43         }
44         memcpy(st,st2,sizeof(st2));
45         cnt=tmp;tmp=0;    
46     }
47     printf("%d\n",f[(1<<n)-1].y>0?1+f[(1<<n)-1].x:f[(1<<n)-1].x);
48     return 0;
49 }

 

posted @ 2016-04-14 14:12  TenderRun  阅读(393)  评论(0编辑  收藏  举报