The simplest Recursion Method: (this algorithm times out .)
// The time complexity is 2 ^ n
# Include <iostream>
# Include <cmath>
# Include <cstring>
# Include <map>
# Include <algorithm>
Using namespace STD;
Const int max = 1001;
Typedef struct
{
Int value;
Int volume;
} Bone;
Bone B [Max];
Int make (int I, Int J) // the I-th item, current remaining capacity J
{
If (I <= 0)
Return 0;
Int R1 = 0, R2 = 0;
If (j> = B [I]. Volume) // The value of the I-th item that can be placed in the backpack
{
R1 = make (I-1, J-B [I]. Volume) + B [I]. value;
}
R2 = make (I-1, J); // The value of the I-th item that is not included in the backpack
If (r1> R2)
Return R1;
Else
Return R2;
}
Int main ()
{
Freopen ("in6.txt", "r", stdin );
Int t, n, V;
Cin> T;
While (t --)
{
Cin> N> V;
For (INT I = 1; I <= N; I ++)
{
Cin> B [I]. value;
}
For (INT I = 1; I <= N; I ++)
{
Cin> B [I]. volume;
}
Int T = make (n, V );
Cout <t <Endl;
}
}
Use Dynamic Planning. The time complexity is N * V (Number * capacity), and the space complexity two-dimensional matrix (N * V) N * V may be greater than 2 ^ n
View plaincopy to clipboardprint?
# Include <iostream>
# Include <cmath>
# Include <cstring>
# Include <map>
# Include <algorithm>
Using namespace STD;
Const int max = 1001;
Typedef struct
{
Int value;
Int volume;
} Bone;
Bone B [Max];
Int f [Max] [Max];
Int main ()
{
Int t, n, V;
Cin> T;
While (t --)
{
Cin> N> V;
For (INT I = 1; I <= N; I ++)
{
Cin> B [I]. value;
}
For (INT I = 1; I <= N; I ++)
{
Cin> B [I]. volume;
}
For (INT I = 0; I <= V; I ++)
{
F [0] [I] = 0;
}
For (INT I = 1; I <= N; I ++)
{
For (Int J = 0; j <= V; j ++)
{
F [I] [J] = f [I-1] [J];
If (j> = B [I]. volume & F [I-1] [J-B [I]. volume] + B [I]. value> F [I] [J])
F [I] [J] = f [I-1] [J-B [I]. Volume] + B [I]. value;
}
}
Cout <F [N] [v] <Endl;
}
}
Simplified matrix algorithm. The time complexity is also N * V, and the space complexity is a one-dimensional array (V ).
View plaincopy to clipboardprint?
# Include <iostream>
# Include <cmath>
# Include <cstring>
# Include <map>
# Include <algorithm>
Using namespace STD;
Const int max = 1090;
Typedef struct
{
Int value;
Int volume;
} Bone;
Bone B [Max];
Int DP [Max];
Int main ()
{
// Freopen ("in6.txt", "r", stdin );
Int t, n, V;
Cin> T;
While (t --)
{
Memset (DP, 0, sizeof (DP ));
Cin> N> V;
For (INT I = 1; I <= N; I ++)
{
Cin> B [I]. value;
}
For (INT I = 1; I <= N; I ++)
{
Cin> B [I]. volume;
}
For (INT I = 1; I <= N; I ++)
{
For (Int J = V; j> = B [I]. Volume; j --)
{
If (DP [J] <DP [J-B [I]. Volume] + B [I]. value)
{
DP [J] = DP [J-B [I]. Volume] + B [I]. value;
}
}
}
Cout <DP [v] <Endl;
}
Return 0;
}