POJ 3624 0-1背包問題 動態規劃

來源:互聯網
上載者:User

    第一道背包問題,0-1背包,參考網上一位大牛寫的做的。狀態方程:dp[i][w] = max{dp[i-1][w], dp[i-1][w-obj[i].wei] + obj[i].val]},但這樣會超記憶體,需要一個空間複雜度的最佳化將dp改為一維,這招看來以後得常用,具體見轉載的《背包九講》。

    明天好好讀讀《背包九講》,在多做幾道dp變形題,練習在於精不在多。

#include <iostream><br />using namespace std;<br />const int mMax = 3500;//待選物品個數<br />const int nMax = 14000;//最大容量<br />struct{<br />int wei,val;<br />}node[mMax];<br />int main(){<br />int n,m,i,w,dp[nMax];<br />cin>>n>>m;//n為物品個數,m為最大容量<br />for (i = 1;i <= n;i++)<br />cin>>node[i].wei>>node[i].val;<br />memset(dp,0,(m+1) * sizeof(int));<br />for (i = 1;i <= n;i++)<br />for (w = m;w >= node[i].wei;w--)//從後向前dp,前面的數會影響後面的<br />if (dp[w] < dp[w - node[i].wei] + node[i].val)<br />dp[w] = dp[w - node[i].wei] + node[i].val;<br />cout << dp[m]<<endl;<br />return 0;<br />} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.