zoukankan      html  css  js  c++  java
  • 洛谷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;
    }
    
  • 相关阅读:
    python定义函数的三种形式
    python函数的返回值
    python函数的调用
    python函数的定义
    python文件操作
    Python2和3字符编码的区别
    python的字符编码
    python异常处理
    python深浅拷贝
    python色彩缤纷的python(改变字体颜色以及样式)
  • 原文地址:https://www.cnblogs.com/lipoicyclic/p/14433148.html
Copyright © 2011-2022 走看看