Meaning of the questions: buy accessories premise is to buy the main pieces, and asked to get the most value for a given amount.
Analysis: dependent knapsack problem template, note that there are not dependent backpack backpack grouping of three for the kind of order, but a post-enumeration of the main pieces, constantly enumeration accessory, purchase a number of different accessories.
Meanwhile, in writing, with the f array represents an array of answers, each j f is the corresponding optimal decision-making, and each enumerate all operations on the array t, and then determine what needs to update the f array.
* Packet backpack is an article grouping, each group of items conflict with each other, can only choose one item in a bag. In fact, the "select all items in a" from become a "select group from the current one", so they each group to conduct a knapsack on it.
* Packet backpack core code:
for ( int K = . 1 ; K <= TS; K ++) // cycle each group for ( int I = m; I> = 0 ; i--) // cycle backpack capacity for ( int J = . 1 ; J < = CNT [K]; J ++) // for each article cycle of the group IF (I> = W [T [K] [J]]) DP [I] = max (DP [I], DP [I - W [T [K] [J]]] + C [T [K] [J]]); // as knapsack as the state transition, the same as the 0-1 knapsack prevent duplicate into the same article ideas
This problem Code:
#include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> using namespace std; const int maxn = 202003; struct node{ int p,v,f; }a[777]; int f[maxn]; int t[maxn]; int main(){ int n,m; scanf("%d%d",&n,&m); for(int i=1; i<=m; i++){ scanf("%d%d%d",&a[i].p,&a[i].v,&a[i].f); a[i].v *= a[i].p; } for(int i=1; i<=m; i++){ //一步 if(!a[i].f){ for(int j=0; j<a[i].p; j++){ t[j] = f[j]; } for(int j=a[i].p; j<=n; j++){ t[j] = f[j - a[i].p]+a[i].v; } for( Int K = . 1 ; K <= m; K ++) { // two steps IF (A [K] .F == I) { for ( int J = n-; J> = A [I] .p; J- -) { // three steps (note that this is not written a plurality of sets of the backpack, the article can be put into the same group) IF (JA [K] .p> = a [I] .p) { // the printf ( "Yes \ n-"); T [J] = max (T [JA [K] .p] + A [K] .v, T [J]); // the printf ("% D% D \ n-", J, T [J]); } } } } for ( int j=a[i].p; j<=n; j++){ f[j] = max(f[j],t[j]); } } } printf("%d\n", f[n]); }