01背包的多种另类解法 第十四届华中科技大学程序设计竞赛决赛同步赛 F Beautiful Land 01背包的多种另类解法

It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
Now HUST got a big land whose capacity is C to plant trees. We have n trees which could be plant in it. Each of the trees makes HUST beautiful which determined by the value of the tree. Also each of the trees have an area cost, it means we need to cost c i area of land to plant.
We know the cost and the value of all the trees. Now HUSTers want to maximize the value of trees which are planted in the land. Can you help them?

输入描述:

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 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int N = 1e4+5;
const int INF=0x3f3f3f3f;
int dp[N]={0};
int v[N];
int w[N];
int main()
{
  int n,m,sum=0,t;
   scanf("%d",&t);
    while(t--){
    scanf("%d%d",&n,&m);
    sum=0;
    for(int i=1;i<=n;i++){
        scanf("%d%d",&w[i],&v[i]);
        sum+=v[i];
    }
    memset(dp,INF,sizeof(dp));
    dp[0]=0;
    for(int i=1;i<=n;i++)
        for(int j=sum;j>=v[i];j--)
        dp[j]=min(dp[j],dp[j-v[i]]+w[i]);
    for(int i=sum;i>=0;i--){
        if(dp[i]<=m){
            printf("%d\n",i);
            break;
        }
     }
    }
    return 0;
}

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;
}

你可能感兴趣的:(ACM_搜索,ACM_背包问题)