zoukankan      html  css  js  c++  java
  • hdu2546 饭卡

    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

    这道题是一道01背包问题,不过要稍微变下形,先用剩下的5元买最贵的东西,然后用m-5元买尽可能多的东西。

    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    #include<math.h>
    #include<vector>
    #include<map>
    #include<queue>
    #include<stack>
    #include<string>
    #include<algorithm>
    using namespace std;
    int f[1006],w[1006];
    int main()
    {
    	int n,m,i,j,maxx;
    	while(scanf("%d",&n)!=EOF && n!=0)
    	{
    		for(i=1;i<=n;i++){
    			scanf("%d",&w[i]);
    		}
    		sort(w+1,w+1+n);
    		maxx=w[n];
    		scanf("%d",&m);
    		if(m<5){
    			printf("%d
    ",m);continue;
    		}
    		if(m==5){
    			printf("%d
    ",m-maxx);continue;
    		}
    		memset(f,0,sizeof(f));
    		for(i=1;i<=n-1;i++){
    			for(j=m-5;j>=w[i];j--){
    				f[j]=max(f[j],f[j-w[i]]+w[i]);
    			}
    		}
    		printf("%d
    ",m-maxx-f[m-5]);
    	}
    	return 0;
    }


  • 相关阅读:
    grunt 使用比较
    一些技术要点
    git 使用笔记
    oo的一些概念
    借用构造函数继承非原型
    bower解决js的依赖管理
    需要了解的一些东西
    一些常用的代码
    js模式(一):单例模式
    写给自己的计划
  • 原文地址:https://www.cnblogs.com/herumw/p/9464743.html
Copyright © 2011-2022 走看看