CH2201 小猫爬山 DFS

题目链接

http://noi-test.zzstep.com/contest/0x20%E3%80%8C%E6%90%9C%E7%B4%A2%E3%80%8D%E4%BE%8B%E9%A2%98/2201%20%E5%B0%8F%E7%8C%AB%E7%88%AC%E5%B1%B1

分析

设状态为 ( n o w , c n t ) (now, cnt) (now,cnt) n o w now now 表示当前要分配第几只猫, c n t cnt cnt 表示已经租用了多少辆缆车;

同时记录下每辆缆车的重量情况,DFS即可。

当前 c n t cnt cnt 若大于等于已求的答案,直接返回;按重量给猫排序,先放重量大的。

AC代码

#include <cstdio>
#include <algorithm>

using namespace std;

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 20;

int n, w, a[maxn], c[maxn], ans = 20;

inline int comp(int a, int b) {
	return a > b;
}

void dfs(int now, int cnt) {
	if (now == n + 1) {
		ans = min(ans, cnt);
		return;
	}
	if (cnt >= ans) return;
	for (int i = 1; i <= cnt; ++i)
		if (c[i] + a[now] <= w) {
			c[i] += a[now];
			dfs(now + 1, cnt);
			c[i] -= a[now];
		}
	c[cnt + 1] = a[now];
	dfs(now + 1, cnt + 1);
	c[cnt + 1] = 0;
}

int main() {
	n = read(), w = read();
	for (int i = 1; i <= n; ++i) a[i] = read();
	sort(a + 1, a + n + 1, comp);
	dfs(1, 0);
	printf("%d", ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值