Elevator Rides

题目描述

There are n people who want to get to the top of a building which has only one elevator. You know the weight of each person and the maximum allowed weight in the elevator. What is the minimum number of elevator rides?

输入

The first input line has two integers n and x: the number of people and the maximum allowed weight in the elevator.

The second line has n integers w1,w2,...,wn: the weight of each person.

Constraints

1 ≤ n ≤ 20

1 ≤ x ≤ 109

1 ≤ wi ≤ x

输出

Print one integer: the minimum number of rides.

样例输入
复制代码
4 10
4 8 6 1
样例输出
复制代码
2

**题目大意:**n个人,只有一台电梯,电梯最大载重为x,为最少需要上几趟

**思路:**n<=20,想到状压dp,定义mask状态,0表示不选,1表示选,用dp[mask]表示选择mask状态的人时,需要的最少趟数,由于每一趟都是最少的趟数,在新添加一个人时,只需要考虑它能不能上最后那一趟电梯,所以还需要记录最后一趟的剩余载重。

另外注意,状压dp中的状态更新后的current可能是由多个mask更新而来的,所以需要最后在与之前的dp[current]进行比较,而不是直接进行更新

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
int w[20];
int dp[1<<20];//最少趟数
int remain[1<<20];//最后一趟还能载多重
int main(){
    int n,x;cin>>n>>x;
    for (int i=0;i<n;i++)
    cin>>w[i];
    memset(dp,0x3f,sizeof(dp));
    dp[0]=0,remain[0]=0;
    for (int mask=0;mask<(1<<n);mask++){
        for (int i=0;i<n;i++){
            if(mask&(1<<i))
            continue;
            int current=mask|(1<<i);
            int tdp,tremain;
            if(remain[mask]>=w[i]){
                tdp=dp[mask];
                tremain=remain[mask]-w[i];
            }
            else{
                tdp=dp[mask]+1;
                tremain=x-w[i];
            }
            if(tdp<dp[current]||(tdp==dp[current]&&tremain>remain[current])){
                dp[current]=tdp;
                remain[current]=tremain;
            }
        }
    }
    cout<<dp[(1<<n)-1];
}
相关推荐
WJSKad12358 分钟前
【DepthPro】实战教程:单目深度估计算法详解与应用
算法
wzqllwy11 分钟前
8 大经典排序算法(Java 实现):原理 + Demo + 核心分析
java·算法·排序算法
We་ct12 分钟前
LeetCode 77. 组合:DFS回溯+剪枝,高效求解组合问题
开发语言·前端·算法·leetcode·typescript·深度优先·剪枝
重生之我是Java开发战士15 分钟前
【递归、搜索与回溯】二叉树中的深度优先搜索:布尔二叉树,求根节点到叶节点数字之和,二叉树剪枝,验证二叉搜索树,第K小的元素,二叉树的所有路径
算法·深度优先·剪枝
篮l球场15 分钟前
矩阵置零
算法
lihihi17 分钟前
P1650 [ICPC 2004 Shanghai R] 田忌赛马(同洛谷2587)
开发语言·算法·r语言
朱一头zcy18 分钟前
[牛客]BC38 变种水仙花
算法
努力学算法的蒟蒻18 分钟前
day105(3.6)——leetcode面试经典150
算法·leetcode·面试
Chan1620 分钟前
LeetCode 热题 100 | 矩阵
java·开发语言·数据结构·算法·spring·java-ee·intellij-idea
钓鱼的肝23 分钟前
[GESP-4.2503.T2]二阶矩阵
c++·算法·矩阵