1. 程式人生 > >【題解】Luogu P3052 【USACO12】摩天大樓裏的奶牛Cows in a Skyscraper

【題解】Luogu P3052 【USACO12】摩天大樓裏的奶牛Cows in a Skyscraper

eat ring real several define courier u+ awt help

叠代加深搜索基礎

題目描述

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.

輸出格式:

  • 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.

輸入輸出樣例

輸入樣例#1: 復制

4 10
5
6
3
7

輸出樣例#1: 復制

3
2 1 3
1 2
1 4

說明

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,當目前深度達到限制深度後驗證當前方案的合理性,更新答案。
    不斷調整搜索深度,直到找到最優解。
    本題中枚舉電梯數num,就是搜索的深度

  • 剪枝: 可證第i奶牛放到i後車廂沒有意義

代碼

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define re register int
using namespace std;
int n, m, c[19], tot(0), ans(0), v[19];
bool dfs(int x, int num){
    for(re i=1;i<=x&&i<=num;++i)
        if(v[i]+c[x]<=m){
            v[i]+=c[x];
            if(x==n) return 1;
            if(dfs(x+1,num)) return 1;
            v[i]-=c[x];
        }
    return 0;
}
int main(){
    scanf("%d%d",&n,&m);
    for(re i=1;i<=n;++i) scanf("%d", &c[i]);
    for(re i=1;i<=n;++i){//枚舉廂數
        memset(v,0,sizeof(v));
        if (dfs(1,i)){
            printf("%d\n",i);
            break;
        }
    }
    return 0;
}
?

【題解】Luogu P3052 【USACO12】摩天大樓裏的奶牛Cows in a Skyscraper