poj-2184Cow Exhibition (01 backpack negative process)

The meaning of problems: n prior cow, each cow each two indices: index and well-wise index S F, S exists and if TS> = 0 and F with TF> = 0 simultaneously satisfied, then the output TS and the maximum sum TF and otherwise outputs 0.

Thinking: knapsack
1. With participation negative, then we need to modify the starting position DP of the array, given the presence of negative, so DP array subscript 1-mid section to process negative to process mid-N interval positive number
issue 2. the initialization, the entire array to a DP minimum value (negative), the starting point 0.
different positive and negative numbers when the backpack 3

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath>


using namespace std;

const int N = 200005;
const int inf = -0x3f3f3f;
int mid = 100000;
int dp[200005];
int v[111];
int w[111];


int main()
{
    int n;
    cin>>n;
    int i,j;
    for(i=1; i<=n; i++)
    {
        scanf("%d %d",&w[i],&v[i]);
    }
    memset(dp,inf,sizeof(dp));
    dp[100000] = 0;
    for(i=1; i<=n; i++)
    {
        if(w[i]>0)
        {
            for(j=N; j>=w[i]; j--)
            {
                dp[j] = max(dp[j],dp[j-w[i]]+v[i]);
            }
        }
        else
        {
            for(j=0; j<N+w[i]; j++)
            {
                dp[j] = max(dp[j],dp[j-w[i]]+v[i]);
            }
        }
    }
    int res = 0;
    for(i=mid; i<N; i++)
    {
        if(dp[i]>0)
            res = max(res,dp[i]+i-mid);
    }
    cout<<res<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44694282/article/details/90411416