帶負值的背包問題poj2184

來源:互聯網
上載者:User

1:選的牛要保證兩個屬性和都要大於0。

2.總和最大。

想到什麼。01背包,一個數要麼不用,要麼用,讓價值最大。

因為會出現負值,並且兩個值均大於0 ,那麼假設第一種屬性已經大於0了--重新設定0點,讓100*1000為0點,過了這個點,就說明選的第一個屬性和大於0了,反之則沒有。那麼這時候就只需要管第二種的屬性了。把第一種當做消耗來算,第二種屬性來算價值(相當於只有花費a,才能得到b。因為a已經在座標體現了。小於100000就為負,否則為正),進行DP。那麼算出來就需要看dp值是否大於0了。01背包一維DP是倒序的。但是當a[i]為負數時,如果依舊倒序,反而遞推式沒有往小跑,因為是dp【j-a[i]】,a【i】為負,j-a反而變大。

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#include<iostream>#include<algorithm>#include<stack>#include<queue>#include<vector>#include<set>#include<map>#include<string>#define nl n<<1#define nr (n<<1)|1using namespace std;typedef long long ll;typedef unsigned long long ull;typedef pair<int,int>P;const int INF=0x3f3f3f3f;const ll INFF=0x3f3f3f3f3f3f3f3f;const double pi=acos(-1.0);const double eps=1e-9;const ll mod=1e9+7;int read(){    int x=0,f=1;char ch=getchar();    while(ch<'0' | ch>'9') {if(ch=='-') f=-1;ch=getchar();}    while(ch>='0' && ch<='9') {x=x*10+ch-'0';ch=getchar();}    return x*f;}void Out(int aa){    if(aa>9)        Out(aa/10);    putchar(aa%10+'0');}int a[105],b[105];int dp[200010];int main(){    int n=read();    for(int i=1;i<=n;i++)scanf("%d%d",&a[i],&b[i]);    memset(dp,-INF,sizeof(dp));    dp[100000]=0;    for(int i=1;i<=n;i++)    {        if(a[i]>0)        {            for(int j=200005;j>=a[i];j--)                dp[j]=max(dp[j],dp[j-a[i]]+b[i]);        }        else        {            for(int j=0;j<=200005+a[i];j++)                dp[j]=max(dp[j],dp[j-a[i]]+b[i]);        }    }    int ans=0;    for(int i=100000;i<=200005;i++)    {        if(dp[i]>0)            ans=max(ans,dp[i]+i-100000);    }    cout<<ans<<endl;    return 0;}

所以這時候讓式子從0開始跑,就對了。具體看代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.