const int MAXN = 101;
const int SIZE = 50001;
int dp[SIZE];
int volume[MAXN], value[MAXN], c[MAXN];
int n, v; // 总物品数,背包容量
// 01背包
void ZeroOnepark(int val, int vol){
for (int j = v ; j >= vol; j--){
dp[j] = max(dp[j], dp[j - vol] + val);}}// 完全背包
void Completepark(int val, int vol){
for (int j = vol; j <= v; j++){
dp[j] = max(dp[j], dp[j - vol] + val);}}// 多重背包
void Multiplepark(int val, int vol, int amount){if (vol * amount >= v){Completepark(val, vol);}else{
int k = 1;
while (k < amount){ZeroOnepark(k * val, k * vol);
amount -= k;
k <<= 1;}if (amount > 0){ZeroOnepark(amount * val, amount * vol);}}}int main(){while (cin >> n >> v){
for (int i = 1 ; i <= n ; i++){
cin >> volume[i] >> value[i] >> c[i]; // 费用,价值,数量
}memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++){Multiplepark(value[i], volume[i], c[i]);}
cout << dp[v] << endl;}
return 0;}
最长公共递增子序列
/*
* 最长公共递增子序列 O(n^2)
* f记录路径,DP记录长度, 用a对b扫描,逐步最优化。
*/
const int N = 1010;
int f[N][N], dp[N];
int gcis(int a[], int la, int b[], int lb, int ans[]){ // a[1...la], b[1...lb]
int i, j, k, mx;memset(f, 0, sizeof(f));memset(dp, 0, sizeof(dp));
for (i = 1; i <= la; i++){memcpy(f[i], f[i-1], sizeof(f[0]));
for (k = 0, j = 1; j <= lb; j++){if (b[j - 1] < a[i - 1] && dp[j] > dp[k]){
k = j;}if (b[j - 1] == a[i - 1] && dp[k] + 1 > dp[j]){
dp[j] = dp[k] + 1,
f[i][j] = i * (lb + 1) + k;}}}
for (mx = 0, i = 1; i <= lb; i++){if (dp[i] > dp[mx]){
mx = i;}}
for (i = la * lb + la + mx, j = dp[mx]; j; i = f[i / (lb + 1)][i % (lb + 1)], j--){
ans[j - 1] = b[i % (lb + 1) - 1];}
return dp[mx];}
最长有序子序列
/*
* 递增(默认)
* 递减
* 非递增
* 非递减 (1)>= && < (2)< (3)>=
*/
const int MAXN = 1001;
int a[MAXN], f[MAXN], d[MAXN]; // d[i] 用于记录 a[0...i] 以 a[i] 结尾的最大长度
int bsearch(const int *f, int size, const int &a){
int l = 0, r = size - 1;
while (l <= r){
int mid = (l + r) / 2;
if (a > f[mid - 1] && a <= f[mid]) // (1){
return mid;}else if (a < f[mid]){
r = mid - 1;}else{
l = mid + 1;}}
return -1;}int LIS(const int *a, const int &n){
int i, j, size = 1;
f[0] = a[0];
d[0] = 1;
for (i = 1; i < n; ++i){if (a[i] <= f[0]) // (2){
j = 0;}else if (a[i] > f[size - 1]) // (3){
j = size++;}else{
j = bsearch(f, size, a[i]);}
f[j] = a[i];
d[i] = j + 1;}
return size;}int main(){
int i, n;
while (scanf("%d", &n) != EOF){
for (i = 0; i < n; ++i){scanf("%d", &a[i]);}printf("%d\n", LIS(a, n)); // 求最大递增 / 上升子序列(如果为最大非降子序列,只需把上面的注释部分给与替换)}
return 0;}
最长公共子序列
const int N = 1010;
int a[N][N];
int LCS(const char *s1, const char *s2){ // s1:0...m, s2:0...n
int m = (int)strlen(s1), n = (int)strlen(s2);
int i, j;
a[0][0] = 0;
for (i = 1; i <= m; ++i){
a[i][0] = 0;}
for (i = 1; i <= n; ++i){
a[0][i] = 0;}
for (i = 1; i <= m; ++i){
for (j = 1; j <= n; ++j){if (s1[i - 1] == s2[j - 1]){
a[i][j] = a[i - 1][j - 1] + 1;}else if (a[i - 1][j] > a[i][j - 1]){
a[i][j]= a[i - 1][j];}else{
a[i][j] = a[i][j - 1];}}}
return a[m][n];}