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];
}
相关推荐
始三角龙2 分钟前
LeetCode hoot 100 -- 缺失的第一个正整数
算法·leetcode·职场和发展
飞Link17 分钟前
深度解析孪生网络(Siamese Network):从原理、技巧到实战应用
算法·数据挖掘·回归
测试狗科研平台27 分钟前
洞悉微观电荷流动,VASP计算电荷密度分布
算法·云计算·开源软件
Orz_Sponge_Bob1 小时前
温州市第三届青少年程序设计竞赛(小学组)题解
算法
Noushiki1 小时前
常见的排序算法
算法·排序算法
gumichef1 小时前
二叉树链式结构的实现
算法·链表·二叉树·队列
战南诚1 小时前
力扣 之 198.打家劫舍
python·算法·leetcode
AllData公司负责人1 小时前
亲测丝滑,体验跃迁|AllData通过集成开源项目StreamPark,实时流任务调度更省心!
java·大数据·数据库·人工智能·算法·实时计算·实时开发平台
计算机安禾1 小时前
【c++面向对象编程】第46篇:CRTP(奇异递归模板模式):静态多态的妙用
开发语言·c++·算法
广州灵眸科技有限公司1 小时前
瑞芯微(EASY EAI)RV1126B 音频电路
开发语言·人工智能·深度学习·算法·yolo·音视频