HDU 2546 飯卡

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   strong   for   

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=2546

 

思路:1.如果餘額小於5,直接輸出,因為小於5買不了任何東西

   2.如果餘額大於5,

    (1)則對所有的菜進行排序,選出其中最大的一個

    (2)將餘額減去5,然後在上面進行01背包。(如果定義餘額為s,那麼體積為s-5,物品個數為n-1,為什麼是n-1呢,因為我們在第一步中去掉了一個最大的)

    (3)將餘額減去01背包的結果再減去那個最大的菜即可(即 餘額-(結果+最大的菜))

 

代碼用一維數組或者二維數組做均可。

代碼如下:

    

#include <iostream>#include <cstring>#include <algorithm>using namespace std;int dp[1001]; inline int max6(int a,int b){ return a>b?a:b;}int main(){    int n,s;    int v[1001];    int i,j;    int max;    while(cin>>n&&n!=0)    {        memset(dp,0,sizeof(dp));        memset(v,0,sizeof(v));        for(i=1; i<=n; i++)        {            cin>>v[i];        }                cin>>s;            sort(v,v+n+1);                if(s<5)        {            cout<<s<<endl;            continue;        }                                for(i=1;i<n; i++)        {            for(j=s-5; j>=v[i]; j--)                    dp[j] = max6(dp[j],dp[j-v[i]]+v[i]);        }                cout<<s-(dp[s-5]+v[n])<<endl;    }            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.