两船载物问题

搜索的话解空间太大,会超时,RT 可以用0~1背包做

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <algorithm>

using namespace std;
int n;
int c1, c2;
int cw ,bestw;
int c[103];
int _max, sum;
int leftw(int t)
{
	int sum =0;
	for(int i = t+1; i<n; i++)
	sum += c[i];
	return sum;
}
void dfs(int step, int cw)
{
	if(step == n)
	{
		if(cw > bestw)
		bestw = cw;
		return;
	}
	sum -= c[step];
	if(cw + c[step] <= c1)
	{
		cw += c[step]; 
		dfs(step+1,cw);
		cw -= c[step];
	}
	if(cw + sum > bestw)
	dfs(step+1,cw);
	sum += c[step];	
}
int main()
{
	while(scanf("%d", &n) != EOF)
	{
		scanf("%d %d",&c1, &c2);
		sum = 0;
		for(int i=0; i<n; i++)
		{
			scanf("%d",&c[i]);
			sum += c[i];
		}
		_max = sum;
		cw = bestw = 0;
		dfs(0, 0);
		if(_max - bestw <=c2)
		printf("YES\n");
		else
		printf("NO\n");
	}
system("pause");
return 0;
}


---------------------------------------------------------------------------------------

#include <stdio.h>   
#include <string.h>   
int list[101];  
int dp[5001];  
int main(){  
    int n, c1, c2, sum, i;  
    while(~scanf("%d%d%d", &n, &c1, &c2)){  
        sum = 0;  
        for(i = 1; i <= n; i++){  
            scanf("%d", &list[i]);  
            sum += list[i];  
        }  
        memset(dp, 0, sizeof(dp));//初始化dp = 0   
        for(i = 1; i <= n; i++)  
            for(int j = c1; j >= list[i]; j--)  
                dp[j] = dp[j] >= dp[j - list[i]] + list[i] ? dp[j] : dp[j - list[i]] + list[i];  
                //寻找在装在j,前i块重物中能容纳的最大,此处有点不容易理解   
        puts(dp[c1] + c2 >= sum ? "YES" : "NO");  
    }  
    return 0;  
}  


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值