Poj3628-DFS/0-1 backpack-DP/enumeration-weak data, more methods

Source: Internet
Author: User

Because the data range is 20, the direct enumeration is 2 ^ 20 and does not time out. Simply find the combination. In N, take 1 and 2 .... N number. You can find a minimum difference.
The following is a combination of algorithms-175 MS
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <math. h>
 
# Define nMax 25
Int N, B;
Int height [nMax];
Int ans;
 
 
Int getSum (int pos)
{
Int sum = 0;
For (int I = 0; I <N; ++ I)
{
If (pos & (1 <I ))
{
Sum + = height [I];
}
}
Return sum;
}
Int main ()
{
While (scanf ("% d", & N, & B )! = EOF)
{
Ans = 0x7FFFFFFF;
For (int I = 0; I <N; ++ I)
{
Scanf ("% d", & height [I]);
}
For (int I = 1; I <(1 <N); ++ I)
{
If (getSum (I) <B)
{
Continue;
}
Int tmp = getSum (I)-B;
If (ans> tmp)
{
Ans = tmp;
}
}
Printf ("% d \ n", ans );
}
Return 0;
}

This question can also be done using 01 backpack dynamic planning-32 MS
[Cpp]
# Include <iostream>
# Include <cstring>
Using namespace std;
Int f [1000050], c [10000];
Int main (){
Int n, v;
While (cin> n> v ){
Memset (f, 0, sizeof (f ));
Memset (c, 0, sizeof (c ));
Int sum = 0;
For (int I = 1; I <= n; ++ I ){
Cin> c [I];
Sum + = c [I];
}
For (int I = 1; I <= n; I ++ ){
For (int j = sum; j> = c [I]; j --)
F [j] = max (f [j], f [j-c [I] + c [I]);
}
For (int I = 1; I <= sum; ++ I ){
If (f [I]> = v ){
Cout <f [I]-v <endl;
Break;
}
}
}
Return 0;
}

 
This question can also be done with the dfs deep Priority Search-32 MS
[Cpp]
# Include <stdio. h>
Int cow [20];
Int B;
Int n;
Int ans = 99999999;
Void DFS (int num, int sum)
{
If (sum> = ans) return;
If (num = n)
{
If (sum> = B) ans = sum;
Return;
}
DFS (num + 1, sum );
DFS (num + 1, sum + cow [num]);
}
Int main ()
{
// Freopen ("input", "r", stdin );
Int I, j, cnt, tmp;
Int sum;
Scanf ("% d", & n, & B );
For (I = 0; I <n; I ++)
Scanf ("% d", & cow [I]);
DFS (0, 0 );
Printf ("% d", ans-B );
Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.