HDU 2602 (0-1背包)

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]);
}

posted @ 2012-07-29 15:36  山路水桥  阅读(136)  评论(0编辑  收藏  举报