01背包(变形)

饭卡

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 53857    Accepted Submission(s): 18264


Problem Description
电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额。如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)。所以大家都希望尽量使卡上的余额最少。
某天,食堂中有n种菜出售,每种菜可购买一次。已知每种菜的价格以及卡上的余额,问最少可使卡上的余额为多少。
 
Input
多组数据。对于每组数据:
第一行为正整数n,表示菜的数量。n<=1000。
第二行包括n个正整数,表示每种菜的价格。价格不超过50。
第三行包括一个正整数m,表示卡上的余额。m<=1000。

n=0表示数据结束。
 
Output
对于每组输入,输出一行,包含一个整数,表示卡上可能的最小余额。
 
Sample Input
1 50 5 10 1 2 3 2 1 1 2 3 2 1 50 0
 
Sample Output
-45 32
 
Source
 
Recommend
lcy   |   We have carefully selected several similar problems for you:   2602  2955  1203  2159  2191
 
这是一个变形的01背包问题,首先如果金额小于5元,剩余金额不变,为已有金额。如果大于等于5元
我们先用5元买最贵的菜。然后用剩下的钱买其他的菜这时就是一个典型的01背包问题了;
求出最大的花费,然后用总金额减去最大的花费即为剩余金额。
//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdio.h>
#include <queue>
#include <stack>;
#include <map>
#include <set>
#include <string.h>
#include <vector>
#define ME(x , y) memset(x , y , sizeof(x))
#define SF(n) scanf("%d" , &n)
#define rep(i , n) for(int i = 0 ; i < n ; i ++)
#define INF  0x3f3f3f3f
#define mod 1000000007
#define PI acos(-1)
using namespace std;
typedef long long ll ;
int dp[1009][1009];
int w[1009];

int main()
{
    int n  , v;
    while(~scanf("%d" , &n) && n)
    {
        for(int i = 1 ; i <= n ; i++)
        {
            scanf("%d" , &w[i]);
        }
        scanf("%d" , &v);
        if(v < 5)
        {
            printf("%d\n" , v);
            continue ;
        }
        v -= 5 ;
        sort(w+1 , w+n+1);
        for(int i = 1 ; i < n ; i++)
        {
            for(int j = v ; j > 0 ; j--)
            {
                if(j >= w[i])
                {
                    dp[i][j] = max(dp[i-1][j] , dp[i-1][j-w[i]]+w[i]);
                }
                else
                    dp[i][j] = dp[i-1][j];
            }
        }
        cout << v + 5 - dp[n-1][v] - w[n] << endl ;
    }

    return 0;
}
 
  
 
 

猜你喜欢

转载自www.cnblogs.com/nonames/p/11669312.html
今日推荐