Bookshelf 2 poj3628 (01 backpack/dfs)

Source: Internet
Author: User

http://poj.org/problem?id=3628

Test instructions: There is a bookshelf, N cow, the farmer wants to put these cows on the shelf, of course, the bookshelf has a fixed height. Now I ask you, among these cows, what is the minimum difference between the heights of some cows and the height of a bookshelf?

Analysis:

Two methods: (1) 01 backpack, calculate the height of all the cattle, and then DP again, and then find a higher than the bookshelf of the minimum value, two number subtraction.

(2) Dfs,dfs (cow's coordinates, the sum of the cow's height), if in the DFS process, the total height of the cow >= bookshelf height, you can ask for the value we need

01 Backpack:

#include <stdio.h>#include<math.h>#include<string.h>#include<ctype.h>#include<stdlib.h>#include<iostream>#include<algorithm>#include<queue>#defineMAXN 1100#defineOO 0x3f3f3f3fusing namespacestd;intdp[maxn*MAXN], W[MAXN];intMain () {intN, M;  while(SCANF ("%d%d", &n, &m)! =EOF) {        intsum =0;  for(intI=1; i<=n; i++) {scanf ("%d", &W[i]); Sum+=W[i]; } memset (DP,0,sizeof(DP));  for(intI=1; i<=n; i++)        {             for(intJ=sum; j>=w[i]; j--) {Dp[j]=max (Dp[j], dp[j-w[i]]+W[i]); }        }        intmins =Oo;  for(intI=1; i<=sum; i++)       {           if(dp[i]>=m) {mins=min (mins, dp[i]-m); }} printf ("%d\n", mins); }    return 0;}
View Code

Dfs:

#include <stdio.h>#include<math.h>#include<string.h>#include<ctype.h>#include<stdlib.h>#include<iostream>#include<algorithm>#include<queue>#defineMAXN 1100#defineOO 0x3f3f3f3fusing namespacestd;intA[MAXN], V[MAXN];intN, m, mins;voidDFS (intXintsum) {    if(Sum >=m) {mins=min (mins, sum-m); return ; }    if(X>n | | mins==0)return ;  for(intI=x; i<=n; i++)    {        if(!V[i]) {V[i]=1; DFS (i+1, sum+A[i]); V[i]=0; }    }}intMain () { while(SCANF ("%d%d", &n, &m)! =EOF) {         for(intI=1; i<=n; i++) scanf ("%d", &A[i]); memset (V,0,sizeof(v)); Mins=Oo; DFS (1,0); printf ("%d\n", mins); }    return 0;}
View Code

Bookshelf 2 poj3628 (01 backpack/dfs)

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.