There are multiple cases. The first line is an integer T(T≤10), which is the number of test cases. For each test case, the first line is two number n(1≤n≤100) and C(1≤C≤108), the number of seeds and the capacity of the land. Then next n lines, each line contains two integer ci(1≤ci≤106) and vi(1≤vi≤100), the space cost and the value of the i-th tree.
For each case, output one integer which means the max value of the trees that can be plant in the land.
题意:01背包
思路:题目中的N较小 M较大为1e8,常规的01背包无法直接解决
1.背包背的是产品的价值(和普通的01背包完全相反)
#include
#include
#include
2.DFS+剪枝(适用于N和M都很大的时候 所以适应性更强) HDU 5887https://blog.csdn.net/consciousman/article/details/52572702
#include
using namespace std;
typedef long long ll;
struct herb{
ll w, v;
double r;
}h[105];
bool cmp(herb x, herb y)
{
return x.r > y.r;
}
ll W, ans;
int n, k;
int check(int i, ll sw, ll sv)
{
for (int j = i; j < k && sw < W; j++){
if (h[j].w+sw <= W) sw += h[j].w, sv += h[j].v;
else sv += h[j].r*(W-sw), sw = W;
}
return sv > ans;
}
void solve(int i, ll sw, ll sv)
{
ans = max(ans, sv);
if (i < k && check(i, sw, sv)){
if (sw+h[i].w <= W) solve(i+1, sw+h[i].w, sv+h[i].v);
solve(i+1, sw, sv);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
scanf("%d %lld", &n, &W);
k = ans = 0;
for (int i = 0; i < n; i++){
ll w, v;
scanf("%lld %lld", &w, &v);
if (w <= W) h[k++] = (herb){w, v, (v+0.0)/w};
}
sort(h, h+k, cmp);
solve(0, 0, 0);
printf("%lld\n", ans);
}
return 0;
}