P2018 「Nescafé26」小猫爬山
时间: 1000ms / 空间: 131072KiB / Java类名: Main

背景

Freda和rainbow饲养了N只小猫,这天,小猫们要去爬山。经历了千辛万苦,小猫们终于爬上了山顶,但是疲倦的它们再也不想徒步走下山了(呜咕>_<)。

描述

Freda和rainbow只好花钱让它们坐索道下山。索道上的缆车最大承重量为W,而N只小猫的重量分别是C1、C2……CN。当然,每辆缆车上的小猫的重量之和不能超过W。每租用一辆缆车,Freda和rainbow就要付1美元,所以他们想知道,最少需要付多少美元才能把这N只小猫都运送下山?

输入格式

第一行包含两个用空格隔开的整数,N和W。
接下来N行每行一个整数,其中第i+1行的整数表示第i只小猫的重量Ci。

输出格式

输出一个整数,最少需要多少美元,也就是最少需要多少辆缆车。

测试样例1

输入

输出

备注

对于100%的数据,1<=N<=18,1<=Ci<=W<=10^8。
Nescafé26

 【题解】

分显然

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
inline void read(int &x){
x = ;char ch = getchar(),c = ch;
while(ch < '' || ch > '') c = ch, ch = getchar();
while(ch <= '' && ch >= '')x = x * + ch - '', ch = getchar();
if(c == '-')x = -x;
}
const int MAXN = + ;
const int INF = 0x3f3f3f3f;
int n,w,weight[MAXN],value[MAXN],ans;
void dfs(int now, int cnt){
if(cnt > ans)return;
if(now == n + )
{
ans = cnt;
return;
}
for(register int i = ;i <= cnt;++ i)
if(weight[i] + value[now] <= w)
weight[i] += value[now], dfs(now + , cnt), weight[i] -= value[now];
weight[cnt + ] = value[now],dfs(now + , cnt + ),weight[cnt + ] = ;
}
int main(){
read(n);read(w);
for(register int i = ;i <= n;++ i) read(value[i]);
ans = INF;
std::sort(value + , value + + n, std::greater<int>());
dfs(, );
printf("%d", ans);
return ;
}

Tyvj2018

05-18 16:05