HDU 2546 飯卡 01背包問題

來源:互聯網
上載者:User

標籤:style   blog   使用   os   io   for   ar   2014   

01背包問題,增加一個額外條件,餘額大於等於5的時候,可以購買任意價格的東西,那麼就把5保留下來買最大價格的物品。

然後轉化為收益的時候要注意初始條件,即沒買東西的時候收益就是餘額,就是所有的錢。這個還是有點難轉換思維的。

最後是要熟悉背包填表,不需要保留選擇的時候,就逆向填表,只需要一維表就可以了,當然也可以使用滾動數組,兩個一維數組就可以了。

走了演算法一圈回來了,AC自動機,線段樹等都學會了,但是遇上這些基礎DP還是不太輕鬆,看來需要繼續打打基礎。主要是思維轉換不夠流暢,速度就不快了。


#include <stdio.h>#include <vector>#include <string.h>#include <algorithm>#include <iostream>#include <string>#include <limits.h>#include <stack>#include <queue>#include <set><span style="white-space:pre"></span>#include <map>using namespace std;const int MAX_N = 1001;int arr[MAX_N], N, M, tbl[MAX_N], maxID;int bag(){if (M < 5) return M;//判特殊情況M -= 5;for (int i = 0; i <= M; i++)tbl[i] = M;for (int i = 0; i < N; i++){if (i == maxID) continue;for (int p = M; p >= arr[i]; p--){tbl[p] = min(tbl[p], tbl[p-arr[i]] - arr[i]);}}return tbl[M] - arr[maxID] + 5;//Watch out: +5}int main(){while (scanf("%d", &N) != EOF && N){maxID = 0;for (int i = 0; i < N; i++){scanf("%d", &arr[i]);if (arr[i] > arr[maxID]) maxID = i;}scanf("%d", &M);printf("%d\n", bag());}return 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.