Test instructions: There are n cows, each cow has a smart value and a fun value, may be positive also may be negative, asked to select N cows to make their smart value and s and fun and F are not negative, and the s+f value is the most demanding.
Analysis:
A good backpack DP problem, we use the smart value as the volume of the item, the fun value as the value of the item, each item can only be taken once, we ask for each backpack volume to exactly fill the volume when the value and the maximum value, that is, when the selected cow Smart value is a value, the maximum value of the fun value. Then for each non-negative backpack volume (the sum of smart values), determine whether the corresponding maximum value (the sum of the fun value) is not negative, if the non-negative indicates that this is a feasible scheme, and then add the two value, take the maximum value of s+f in all feasible schemes.
Also note that since the backpack volume is exactly full, all subscript non 0 F array elements to be assigned a negative infinity, but considering the-maxlongint minus a number will be a problem, so the assignment is larger than its negative value.
Code:
Programexhibition;varB:Array[0.. +] ofLongint; F:Array[-100000..100000] ofLongint; N,i,m,j,h1,h2,ans:longint;functionMax (x,y:longint): Longint;begin ifX>y ThenMax:=xElsemax:=y;End;beginREADLN (n); fori:=1 toN Do beginreadln (A[i],b[i]); ifA[i]>0 Thenh1:=h1+A[i]; ifa[i]<0 Thenh2:=h2+A[i]; End; forI:=h2 toH1 Do ifI<>0 Thenf[i]:=-(Maxlongint)Div 3; fori:=1 toN Do ifA[i]>0 Then begin forJ:=h1DowntoH2 Do ifJ-a[i]>=h2 ThenF[j]:=max (F[j],f[j-a[i]]+b[i])ElseBreak ; End Else begin forJ:=h2 toH1 Do ifJ-a[i]<=h1 ThenF[j]:=max (F[j],f[j-a[i]]+b[i])ElseBreak ; End; fori:=0 toH1 Do iff[i]>=0 ThenAns:=max (ans,f[i]+i); Writeln (ans);End.
View Code
POJ 2184:cow Exhibition (01 backpack variant)