Evanyou Blog 彩带

  题目传送门

摩天大楼里的奶牛

题目描述

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.


  分析:

  因为$n$的范围很小,所以可以想到迭代加深搜索(当然状压DP也可以,但是蒟蒻DP太菜了。。),枚举需要的分组数,然后直接dfs,只要能丢进去就丢进去,直到搜到底,然后回溯重复,知道找到最优结果。

  Code:

//It is made by HolseLee on 24th July 2018
//Luogu.org P3052
#include<bits/stdc++.h>
using namespace std;

int  n,w,a[20],e[20];

inline bool dfs(int x,int tot)
{
    for(int i=1;i<=min(x,tot);i++){
        if(a[x]+e[i]<=w){
            e[i]+=a[x];
            if(x==n)return 1;
            if(dfs(x+1,tot))return 1;
            e[i]-=a[x];
        }
    }
    return 0;
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>w;
    for(int i=1;i<=n;i++)cin>>a[i];
    for(int i=1;i<=n;i++){
        if(dfs(1,i)){
            printf("%d
",i);
            break;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/cytus/p/9362163.html