0/1背包二维费用---国科大卜东波老师算法作业

Problem Description

There is a server which has the disk space of M and the memory of N. Given some tasks, the ii-th task needs the disk space of XiXi and the memory of Yi, and it can serve UiUi users. Design an algorithm and implement it to find out the maximum number of users that this server can serve simultaneously.

Input

The first line of input contains three integers M, N and K, which denote the total disk space, the total memory and the number of tasks. The next K lines are the disk space need, the memory need and the number of users served of tasks. (1 ≤ M, N ≤ 1000 , K≤1000, and Ui ≤ 100000)

在这里插入图片描述

#include <iostream>
using namespace std;
#include<algorithm>
const int N = 100;
int Memo[N];
int Disk[N];
int User[N];
int dp[101][101][101];
int main()
{
  int M,N,K;
  cin >> M>>N>>K;
  for (int i = 1; i <=K; i++) {
		  cin >> Disk[i]>>Memo[i]>>User[i];
  }
  for (int i = 1; i <= K; i++)
  {
	  for (int j = 1; j <= M; j++)
		  for (int k = 1; k <= N; k++)
		  {
			  if (j >= Disk[i] && k >= Memo[i])
				  dp[i][j][k] = max(dp[i - 1][j][k], dp[i - 1][j - Disk[i]][k - Memo[i]] + User[i]);
			  else
				  dp[i][j][k] = dp[i - 1][j][k];
		  }
  }
  cout<< dp[K][M][N];
}
优化二维数组
#include <iostream>
using namespace std;
#include<algorithm>
const int N = 1000;
int Memo[N];
int Disk[N];
int User[N];
int dp[1001][1001];
int main()
{
  int M,N,K;
  cin >> M>>N>>K;
  for (int i = 1; i <=K; i++) {
		  cin >> Disk[i]>>Memo[i]>>User[i];
  }

  for (int i = 1; i <= K; i++)
  {
	  for (int j = M; j >= 1; j--)
		  for (int k = N; k >= 1; k--)
		  {

			  if (j >= Disk[i] && k >= Memo[i])
				  dp[j][k] = max(dp[j][k], dp[j - Disk[i]][k - Memo[i]] + User[i]);
			  else
				  dp[j][k] = dp[j][k];

		  }
  }
  cout<< dp[M][N];
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值