Algorithm: POJ 3628 Bookshelf 2 (DFS, 01 backpack)

Source: Internet
Author: User

The main effect of the topic:

There are n numbers (1~100w), and now there is a number b,1<=b<=s (S is the sum of n digits). To select some number combinations from n digits, the sum of the numbers and x of the combined number is greater than or equal to B, what is the smallest x-b of all x?

Ideas:

Just beginning to see this problem, found that the number is so large that the memory is not enough to use a backpack. and n Max only 20, so directly with dfs+ minus 0MS ...

Then with the backpack, opened the 2000w+ array, memset initialization, decisively mle ... Then looked at the next discuss, found that using memset will add a lot of extra memory.

So instead of initializing for the For loop, the memory is sufficient. And then there's the Naked 01 backpack.

Something:

The data is enough water, DP Open 20W array is over, the complexity of violent 2^20 is also no pressure

DFS + minus 0MS:

#include <iostream>  
#include <queue>  
#include <cstdio>  
#include <cstring>  
#include <cmath>  
      
typedef long long Int64;  
      
const int MAXN = 1000010;  
const int INF = 0X3F3F3F3F;  
int n, b;  
int h[25];  
int sum[25];  
int ans;  
      
void Dfs (int cur, int tol) {  
    if (cur>n+1 | | | ans==b) return;  
    if (tol >= ans) return;  
    if (tol >= b) {  
        ans = min (tol, ans);  
        return;  
    }  
    if (tol + sum[n]-sum[cur-1] < b) return  
        ;  
      
    DFS (cur+1, tol);  
    DFS (cur+1, tol+h[cur]);  
int main () {  
      
      
    while (~scanf ("%d%d", &n, &b)) {  
      
        sum[0] = 0;  
        for (int i=1; i<=n; ++i) {  
            scanf ("%d", &h[i]);  
            if (i==0) sum[0]=h[i];  
            else sum[i] = Sum[i-1]+h[i];  
        }  
      
        ans = INF;  
        DFS (1, 0);  
        printf ("%d\n", 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.