01 Backpack: HDU2546 Fanka

Problem Description
UESTC headquarters cafeteria meal card has a very strange design that determine the balance prior to purchase. Before buying a product if the remaining amount on the card is greater than or equal to $ 5, it will be able to buy success (even after buying the card balance is negative), or can not buy (even if the amount is sufficient). So we all want to try to keep a minimum balance on the card.
One day, there are n canteen sold vegetables, vegetables can be purchased each time. Known vegetables every price and the balance on the card, can at least ask how much the balance on the card.

Input
multiple sets of data. For each set of data:
a first behavior positive integer n, it represents the number of dishes. n <= 1000.
The second row includes n a positive integer representing the price per vegetables. Price not more than 50.
The third row includes a positive integer m, represents the balance on the card. m <= 1000.
n = 0 indicates the end of data.

Output
For each input and output line, comprising an integer, represent the possible minimum 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

This question is the question 01 backpack, but the most strange thing is that the problem of output, he asked that the minimum value, just started not really know
later realized he meant that up to go out to spend much money, and the best is negative, that is, with the last remnant of a minimum of five dollars, to buy the most expensive dish, and then the rest of the money
all spent (that is, and as a backpack, select a menu loaded or not loaded backpack into, max [V- dishes money] which is selected from f [i] [v] = {f [i] [v], f [i-1] + money dishes
can become a dimension F [v] = max (F [v], F [v- cost of food] + dish of money])

#include<stdio.h>
#include<string.h>
//#include <stdbool.h>
#include <algorithm>
#include<queue>
using  namespace std;
//饭卡问题,
int main()
{
    int i,j,sum;
    int cai[100]={0};//菜的价格
    int v,n;//分别代表卡里余额和菜的数量
    int f[100]={0};//这个代表容量为某个值的最大价格
    //先输入菜的数量
    while(scanf("%d",&n)!=EOF&&n!=0){

    //输入每个菜的价格
    for(i=0;i<n;i++){
        scanf("%d",&cai[i]);
    }
    //再输入余额
    scanf("%d",&v);
    //先判断余额是否大于5,如果不大于,那就只能值这个钱了
    if(v<5){
        printf("%d",v);
    }
    else{
        //这里留下最后五块去买价格最高的菜
        //对菜进行排序
        sort(cai,cai+n);//从小到大排
        //然后开始01背包,实现最大值,在这里的话,是每种菜只能购买一次的
        for(i=0;i<n-1;i++){
            for(j=v-5;j>=cai[i];j--){
                f[j]=max(f[j],f[j-cai[i]]+cai[i]);
            }
        }
        //最后怎么计算这个最小余额,就是m-F[m-5]-最高的菜价
        sum=v-f[v-5]-cai[n-1];
        printf("%d\n",sum);
    }


    }

}

Published 72 original articles · won praise 5 · Views 2814

Guess you like

Origin blog.csdn.net/qq_41115379/article/details/104918229