小猫爬山
题目描述
Freda 和 rainbow 饲养了
Freda 和 rainbow 只好花钱让它们坐索道下山。索道上的缆车最大承重量为
输入格式
第一行包含两个用空格隔开的整数,
输出格式
输出一个整数,最少需要多少美元,也就是最少需要多少辆缆车。
样例 #1
样例输入 #1
5 1996
1
2
1994
12
29样例输出 #1
2题解
dfs+回溯
code
c++
//
// Created by 黄书恒1 on 2024/10/5.
//
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<map>
#include<unordered_set>
using namespace std;
#define ll long long
#define ull unsigned long long
#define endl '\n'
const int N = 30;
const int mod = 1e9 + 7;
const ll inf = 1e18;
//int d[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};// 上右下左
int a[N], cnt, sum[N], ans = N, n, w;
void dfs(int u) {
if (cnt >= ans) {
return;
}
if (u == n) {
//枚举完最后一只猫 边界
ans = cnt;
return;
}
for (int i = 0; i < cnt; i++) {
//枚举所有的车
if (sum[i] + a[u] <= w) {
sum[i] += a[u]; //装进第i辆车
dfs(u + 1); //接着搜下一只
sum[i] -= a[u]; //回溯
}
}
sum[cnt++] = a[u]; //新开一辆车 当前这只猫独自做一个车
dfs(u + 1);
sum[--cnt] = 0;
}
void solve() {
cin >> n >> w;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n, greater<int>());
dfs(0);
cout << ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
//cin >> _;
while (_--) {
solve();
}
return 0;
}