【HDU2546】Meal card (01 backpack)

Description

The meal card in the cafeteria of the University of Electronic Science and Technology of China has a very strange design, that is, to determine the balance before purchasing. If the remaining amount on the card is greater than or equal to 5 yuan before purchasing a product, the purchase must be successful (even if the balance on the card is negative after purchase), otherwise the purchase cannot be made (even if the amount is sufficient). So everyone wants to minimize the balance on the card.
One day, there are n kinds of vegetables for sale in the canteen, and each dish can be purchased once. Knowing the price of each dish and the balance on the card, ask how much the minimum balance on the card can be.

Input

Multiple sets of data. For each group of data: the
first line is a positive integer n, which represents the number of dishes. n<=1000.
The second line contains n positive integers, indicating the price of each dish. The price does not exceed 50.
The third line contains a positive integer m, which represents the balance on the card. m<=1000.

n=0 means the end of the data.

Output

For each group of input, one line of output contains an integer that represents the smallest possible balance on the card.

Sample Input

1
50
5
10
1 2 3 2 1 1 2 3 2 1
50
0

Sample Output

-45
32

Idea: Sort the prices of all dishes first, leave 5 yuan to buy the most expensive, and then put the balance on the card m-5. State transition equation: dp[j]=max( dp[j],dp[j-price[i]]+price[i] );

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"

using namespace std;

int cmp( int a,int b )
{
    return a<b;
}

int main()
{
    int n,m,i,j;
    while( ~scanf("%d",&n),n )
    {
        int dp[2016]={0},price[2016]={0};
        for( i=1;i<=n;i++ )
        scanf("%d",&price[i]);
        sort(price+1,price+1+n,cmp);
        int MAX = price[n];
        scanf("%d",&m);
        if( m<5 )
        {
            printf("%d\n",m);
            continue;
        }
        m -=5;
        for( i=1;i<n;i++ )
           for( j=m;j>=price[i];j-- )
           {
            dp[j]=max( dp[j],dp[j-price[i]]+price[i] );
           }

        printf("%d\n",m+5-MAX-dp[m]);

    }
    return 0;
}

Guess you like

Origin blog.csdn.net/thesprit/article/details/50958755