Question: Pedro bought two different brands of chocolate. He found some small boxes. He was going to separate the chocolate and put it in a small box for his friends;
In order not to be found by friends to save money, only the same brand of chocolate can be placed in each small box.
Analysis: DP, 01 backpack.
Here, each small box serves as an item, and the first chocolate serves as a box, recording the precursor (PATH) of each box );
Then, enumerate all the states of the first chocolate, and determine whether the second chocolate can hold the remaining small boxes;
Find the valid information and output the path in reverse order.
Note: At that time, the zoj's 50th dp o (queue _ Queue) O ~
#include <stdio.h> #include <stdlib.h>#include <string.h>bool F[ 1001 ];int c[ 1001 ];int m[ 1001 ];void print( int s, int d ){ if ( s > c[ m[ s ] ] ) { print( s-c[ m[ s ] ], d+1 ); printf(" %d",m[ s ]); }else printf("%d %d",d,m[ s ]);}int main(){ int M,L,N; while ( scanf("%d%d",&M,&L) && (M+L) ) { scanf("%d",&N); int sum = 0; int mal = M+L; for ( int i = 1 ; i <= N ; ++ i ) { scanf("%d",&c[ i ]); sum += c[ i ]; } memset( F, false, sizeof( F ) ); F[ 0 ] = true; for ( int i = 1 ; i <= N ; ++ i ) for ( int j = M ; j >= c[ i ] ; -- j ) if ( F[ j-c[ i ] ] && !F[ j ] ) { F[ j ] = true; m[ j ] = i; } int space = -1; for ( int i = 0 ; i <= M ; ++ i ) if ( F[ i ] && L >= sum-i ) { space = i; break; } if ( space != -1 ) { if ( space ) print( space, 1 ); else printf("0"); }else printf("Impossible to distribute"); printf("\n"); } return 0;}
Zoj 1520-duty free shop