Title description:
Divers must use special equipment for diving. He has a cylinder with 2 gases: one for oxygen and one for nitrogen. Various amounts of oxygen and nitrogen are required to allow divers to dive to the depths. The diver has a certain number of cylinders. Each cylinder has a weight and gas capacity. A diver needs a certain amount of oxygen and nitrogen in order to complete his job. What is the minimum total weight of the cylinder he needs to complete the job?
Example: The diver has 5 cylinders. The three numbers in each row are: the amount of oxygen and nitrogen (liters) and the weight of the cylinder:
3 36 120
10 25 129
5 50 250
1 45 130
4 20 119
If the diver needs 5 liters of oxygen and 60 liters of nitrogen, the total weight The minimum is 249 (1, 2 or 4, 5 cylinders).
Your task is to calculate the lowest value of the cylinder weight that the diver needs to complete his work.
enter:
The first line has 2 integers m, n (1≤m≤21, 1≤n≤79). They indicate the amount of oxygen and nitrogen required for each.
The second line is an integer k (1≤n≤1000) representing the number of cylinders.
The following k rows, each row includes ai, bi, ci (1≤ai≤21, 1≤bi≤79, 1≤ci≤800) 3
integers. These are: the capacity of oxygen and nitrogen in the i-th cylinder and the cylinder weight.
Output:
Only one row contains an integer, which is the lowest value of the sum of the weights of the cylinders required by the diver to complete the work.
Ideas:
This is actually a two-dimensional cost knapsack problem. If the cost is increased by one dimension, the state only needs to be increased by one dimension. This translates into a common knapsack problem. The only difference is that when oxygen and nitrogen exceed the demand, they directly equal the demand.
Here is a detailed explanation of the backpack problem: a detailed explanation of the backpack problem
- Let f[i][v][u] be the maximum value that can be obtained when two prices v and u are paid for the first i item.
State transition equation: f[i][v][u]=max(f[i][v][u],f[i-1][va[i]][ub[i]]+c[i ]) - As the 01 knapsack is transformed into a one-dimensional problem, it is
transformed into a two-dimensional f[v][u]=max(f[v][u],f[va[i]][ub[i]]+c[i] )
Look at the code below :
#include <iostream>
#include <cstring>
using namespace std;
int a[1005],b[1005],c[1005],dp[105][105];
int main()
{
int m,n,k;
cin>>m>>n;
cin>>k;
for(int i=0;i<k;i++)
{
cin>>a[i]>>b[i]>>c[i];
}
memset(dp,127,sizeof(dp));//把f初始化为一个很大的整数
dp[0][0]=0;//o2为0,n2为0时,重量为0
for(int i=0;i<k;i++)
{
for(int j=m;j>=0;j--)
{
for(int l=n;l>=0;l--)
{
int d1=j+a[i];//O2 和01背包不同,它的a[i]和b[i]是可以超过的
int d2=l+b[i];//N2
if(d1>m) d1=m;//若氮 和氧含量超过需求,直接等于需求
if(d2>n) d2=n;
dp[d1][d2]=min(dp[d1][d2],dp[j][l]+c[i]);
}
}
}
cout<<dp[m][n]<<endl;
return 0;
}