zoukankan      html  css  js  c++  java
  • 背包

     1 // 01背包 ==========================================
     2 
     3 memset(f, 0xcf, sizeof(f)); // -INF
     4 f[0][0] = 0;
     5 for (int i = 1; i <= n; i++) {
     6     for (int j = 0; j <= m; j++)
     7         f[i][j] = f[i - 1][j];
     8     for (int j = v[i]; j <= m; j++)
     9         f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i]);
    10 }
    11 
    12 int f[2][MAX_M+1];
    13 memset(f, 0xcf, sizeof(f)); // -INF
    14 f[0][0] = 0;
    15 for (int i = 1; i <= n; i++) {
    16     for (int j = 0; j <= m; j++)
    17         f[i & 1][j] = f[(i - 1) & 1][j];
    18     for (int j = v[i]; j <= m; j++)
    19         f[i & 1][j] = max(f[i & 1][j], f[(i - 1) & 1][j - v[i]] + w[i]);
    20 }
    21 int ans = 0;
    22 for (int j = 0; j <= m; j++)
    23     ans = max(ans, f[n & 1][j]);
    24 
    25 int f[MAX_M+1];
    26 memset(f, 0xcf, sizeof(f)); // -INF
    27 f[0] = 0;
    28 for (int i = 1; i <= n; i++)
    29     for (int j = m; j >= v[i]; j--)
    30         f[j] = max(f[j], f[j - v[i]] + w[i]);
    31 int ans = 0;
    32 for (int j = 0; j <= m; j++)
    33     ans = max(ans, f[j]);
    34 
    35 
    36 // 完全背包 ==========================================
    37 
    38 int f[MAX_M+1];
    39 memset(f, 0xcf, sizeof(f)); // -INF
    40 f[0] = 0;
    41 for (int i = 1; i <= n; i++)
    42     for (int j = v[i]; j <= m; j--)
    43         f[j] = max(f[j], f[j - v[i]] + w[i]);
    44 int ans = 0;
    45 for (int j = 0; j <= m; j++)
    46     ans = max(ans, f[j]);
    47 
    48 
    49 // 多重背包,直接拆分 ==========================================
    50 
    51 unsigned int f[MAX_M+1];
    52 memset(f, 0xcf, sizeof(f)); // -INF
    53 f[0] = 0;
    54 for (int i = 1; i <= n; i++)
    55     for (int j = 1; j <= c[i]; j++)
    56         for (int k = m; k >= v[i]; k--)
    57             f[k] = max(f[k], f[k - v[i]] + w[i]);
    58 int ans = 0;
    59 for (int i = 0; i <= m; i++)
    60     ans = max(ans, f[i]);
    61 
    62 // 分组背包 ==========================================
    63 
    64 memset(f, 0xcf, sizeof(f));
    65 f[0] = 0;
    66 for (int i = 1; i <= n; i++)
    67     for (int j = m; j >= 0; j--)
    68         for (int k = 1; k <= c[i]; k++)
    69             if (j >= v[i][k])
    70                 f[j] = max(f[j], f[j - v[i][k]] + w[i][k]);
  • 相关阅读:
    Linux下date命令,格式化输出,时间设置
    Linux scp复制文件,不需要输入密码的技巧
    Linux中cp和scp命令的使用方法
    Linux定时任务系统 Cron
    Eclipse启动Tomcat后无法访问项目
    eclipse下tomcat插件配置说明
    RPM方式安装MySQL5.6和windows下安装mysql解压版
    shell script练习
    Eclipse Java注释模板设置详解
    mysql备份还原数据库
  • 原文地址:https://www.cnblogs.com/universeplayer/p/10660093.html
Copyright © 2011-2022 走看看