[1, 1372] Do What
Time Limit: 1000 MS memory limit: 65535 K
Problem description
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
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 ).
Output
The minimum time of you cost, if there is no answer, print '-1 '.
Sample Input
3
1 2 3
10
3
1 4 7
6
Sample output
-1
7
Prompt
No source
Hungar operation
Obtain any number from n so that the sum of these numbers is greater than T and minimum.
Ideas:
01 The value closest to T in the backpack Process
View code in detail
[Cpp]
# Include <stdio. h>
# Include <string. h>
Int n, t, ans;
Int val [105];
Int dp [10000];
Void _ 01 bag (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)
_ 01 bag (sum );
Else printf ("-1 \ n ");
}
Return 0;
}
# Include <stdio. h>
# Include <string. h>
Int n, t, ans;
Int val [105];
Int dp [10000];
Void _ 01 bag (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)
_ 01 bag (sum );
Else printf ("-1 \ n ");
}
Return 0;
}