• HDU 2602 (01背包)


    http://acm.hdu.edu.cn/showproblem.php?pid=2602

    简单的0-1背包问题

    代码如下:

    #include <cstdio>
    #include <cstring>
    using namespace std;

    int value[1001], volume[1001];
    int record[1001][1001];

    void knapsack(int n, int v);

    int main()
    {
      int i, j;
      int n, v, ncase;
      scanf("%d", &ncase);
      for(i = 0; i < ncase; i++)
      {
        scanf("%d%d", &n, &v);
        memset(record, 0, sizeof(record));
        for(j = 1; j <= n; j++)
        {
          scanf("%d", &value[j]);
        }
        for(j = 1; j <= n; j++)
        {
          scanf("%d", &volume[j]);
        }
        knapsack(n, v);
      }
      return 0;
    }

    void knapsack(int n, int v)
    {
      int i, j;
      for(i = 1; i <= n; i++)
      {
        for(j = v; j >= 0; j--)
        {      

          if(j < volume[i])
          {
            record[i][j] = record[i - 1][j];
          }

          else if(record[i - 1][j - volume[i]] + value[i] > record[i - 1][j])
          {
            record[i][j] = record[i - 1][j - volume[i]] + value[i];
          }
          else
          {
            record[i][j] = record[i - 1][j];
          }
        }
      }
      printf("%d\n", record[n][v]);
    }

    可进行空间优化:

    #include <cstdio>
    #include <cstring>
    using namespace std;

    int value[1001], volume[1001];
    int record[1001];

    void knapsack(int n, int v);

    int main()
    {
      int ncase;
      int n, v;
      int i, j;
      scanf("%d", &ncase);
      for(i = 0; i < ncase; i++)
      {
        scanf("%d%d", &n, &v);
        memset(record, 0, sizeof(record));
        for(j = 0; j < n; j++)
        {
          scanf("%d", &value[j]);
        }
        for(j = 0; j < n; j++)
        {
          scanf("%d", &volume[j]);
        }
        knapsack(n, v);
      }
      return 0;
    }

    void knapsack(int n, int v)
      {
        int i, j;
        for(i = 0; i < n; i++)
        {
          for(j = v; j >= volume[i]; j--)
          {
            if(record[j - volume[i]] + value[i] > record[j])
            {
              record[j] = record[j - volume[i]] + value[i];
            }
          }
        }
        printf("%d\n", record[v]);
    }

  • 相关阅读:
    create joint
    delphi 使用parent让进度条上显示文字
    abSymMeshMEL.txt
    ini写配置信息
    CreateBindGroupNode.txt
    CreateaJointCurve.txt
    09 IKFKMatch.txt
    TIF_to_MAP.BAT
    ImportBVHv20.txt
    FormatDateTime 一段以时间为命令的代码
  • 原文地址:https://www.cnblogs.com/10jschen/p/2614047.html
Copyright © 2020-2023  润新知