例题:SDNUOJ:1033采药:http://www.acmicpc.sdnu.edu.cn/problem/show/1033
方法一:用一维数组实现:
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stdlib.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;
int a[1005];
int main()
{
int t,n;
cin >> t >> n;
for (int i=1;i<=n;i++) //个数
{
int x,y; //采药时间、这个药的价值
cin >> x >> y;
for (int j=t;j>=x;j--) //一定是从最高向最低进行更新
{
a[j]=max(a[j],a[j-x]+y);
}
}
cout << a[t] << endl;
return 0;
}
方法二:用二维数组实现:
a[i][j]表示从i个物品里面选出不大于j重量的最大价值
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stdlib.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;
int a[1005][1005];
int main()
{
int t,n;
cin >> t >> n;
for (int i=1;i<=n;i++) //个数
{
int x,y; //采药时间+这个药的价值
cin >> x >> y;
for (int j=1;j<=t;j++)
{
if(j<x) a[i][j]=a[i-1][j];
else a[i][j]=max(a[i-1][j],a[i-1][j-x]+y); //最主要的转换公式
}
}
cout << a[n][t] << endl;
return 0;
}
例题:Luogu 2925 干草出售
体积和价值一样,直接套用前面的一维数组实现方法就可以了。
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stdlib.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;
int a[50005];
int main()
{
int t,n;
cin >> t >> n;
for (int i=1;i<=n;i++) //个数
{
int x;
cin >> x;
for (int j=t;j>=x;j--)
{
a[j]=max(a[j],a[j-x]+x);
}
}
cout << a[t] << endl;
return 0;
}



京公网安备 11010502036488号