Loading

洛谷P5194 [USACO05DEC]Scales S (搜索/剪枝)

注意到“这一行中从第3个砝码开始,每个砝码的质量至少等于前面两个砝码(也就是质量比它小的砝码中质量最大的两个)的质量的和。” 斐波那契数列增长速度很快,大约n = 40的时候就到了int的最大值了,因此完全可以搜索。

注意剪枝!

#include <iostream>
#include <algorithm>
using namespace std;
int n;
long long c, a[1005], ans = 0;
long long sum[1005];
bool cmp(int a, int b)
{
	return a > b;
}
void dfs(long long now, long long tot)
{
	if(tot * 1ll + (sum[n] - sum[now - 1]) <= c * 1ll)//如果加上后面所有的都小于c
	{
		ans = max(ans, tot + sum[n] - sum[now - 1]);
		return;
	}
	if(now == n + 1)//边界
	{
		if(tot <= c)
		{
			ans = max(ans, tot);
		}
		return;
	}
	if(tot * 1ll + sum[n] - sum[now - 1] < 1ll * ans) return;//加上后面所有的都无法超过已知最大值
	dfs(now + 1, tot);
	if(tot + a[now] <= c) dfs(now + 1, tot + a[now]);//加上当前不会超的话再继续搜!一定要有这个判定
}
int main()
{
	freopen("data.txt", "r", stdin);
	cin >> n >> c;
	for(int i = 1; i <= n; i++) 
	{
		cin >> a[i];
	}
	sort(a + 1, a + n + 1, cmp);//先搜大的,优化搜索顺序
	for(int i = 1; i <= n; i++) 
	{
		sum[i] = sum[i - 1] + a[i];
	} 
	dfs(1, 0);
	cout << ans;
	return 0;
}
posted @ 2021-02-22 21:51  脂环  阅读(160)  评论(0编辑  收藏  举报