搜索的话解空间太大,会超时,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;
}