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