宁波工程学院[1372] Do What n个数中取出某些数使得和大于T且和最小

  • [1372] Do What

  • 时间限制: 1000 ms 内存限制: 65535 K
  • 问题描述
  • There are n numbers of business, different business will cost you different times. But you need not to finish all of them, just it is ok when you finish some of them that you spend more than T minutes(do not include T minutes).
    So, can you find the way to cost the minimum time when pass T times?
  • 输入
  • Input until EOF.
    First line will contain a positive integer n(1 <= n <= 100) means the number of businesses.
    Next line follows n positive integers ti(1 <= ti <= 10), means the time of each business you will cost.
    Last line is a integer T(1 <= T <= 1000).
  • 输出
  • The minimum time of you cost, if there is no answer, print '-1'.
  • 样例输入
  • 3
    1 2 3
    10
    3
    1 4 7
    6
    
  • 样例输出
  • -1
    7
    
  • 提示
  • 来源
  • Hungar
  • 操作

     

     

    题意: 从n个数中取出任意个 数字 使得这些数字的和大于T且和最小

     

    思路:

    01背包  背包过程中取离T最近的值

     

    详细看代码

    #include<stdio.h>
    #include<string.h>
    int n,t,ans;
    int val[105];
    int dp[10000];
    void _01bag(int v)
    {
    	int i,j;
    	memset(dp,0,sizeof(dp));
    	for(i=0;i<n;i++)
    		for(j=v;j>=val[i];j--)
    			if(dp[j]<dp[j-val[i]]+val[i])
    			{
    				dp[j]=dp[j-val[i]]+val[i];
    				if(dp[j]>t&&ans>dp[j]-t) ans=dp[j]-t;
    			}
    			printf("%d\n",ans+t);
    }
    int main()
    {
    	int i;
    	while(scanf("%d",&n)!=EOF)
    	{
    		ans=999999999;
    		int sum=0;
    		for(i=0;i<n;i++)
    		{
    			scanf("%d",&val[i]);
    			sum+=val[i];
    		}
            scanf("%d",&t);
    		if(sum>t)
    		   _01bag(sum);
    		else printf("-1\n");
    	}
    	return 0;
    }      
    
    
    
    


     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值